3 回答

TA貢獻1773條經驗 獲得超3個贊
由于可以有無限數量的分支,您可能應該有一個遞歸解決方案。我盡了最大努力得到了這段代碼:
$arr = ['Accessories/Apron', 'Accessories/Banners', 'Accessories/Belts','Brand/Brand1','Brand/Brand2',
'Apparel/Men/Belts', 'Apparel/Men/Socks', 'Apparel/Women/Leggings'];
$final = [];
foreach ($arr as $branch) {
$temp = branchRecursive($branch);
$final = array_merge_recursive($final, $temp);
}
function branchRecursive($branch) {
// explode only first
$newBranch = explode('/', $branch, 2);
// A leaf, no more branches
if(count($newBranch) != 2) {
return $newBranch[0];
}
$array [ $newBranch[0] ]= branchRecursive($newBranch[1]);
return $array;
}
它返回這個:
Array
(
[Accessories] => Array
(
[0] => Apron
[1] => Banners
[2] => Belts
)
[Brand] => Array
(
[0] => Brand1
[1] => Brand2
)
[Apparel] => Array
(
[Men] => Array
(
[0] => Belts
[1] => Socks
)
[Women] => Leggings
)
)
與您的代碼唯一不同的是
[Women] => Leggings
代替
[0] => Leggings
但我想睡覺,但我的腦袋不工作,所以如果有人能指出要改變的地方,我將不勝感激。我希望這不是什么大問題:)

TA貢獻1859條經驗 獲得超6個贊
此代碼使您能夠創建任意數量的子分支。
$source = array('Accessories/Apron ' ,
'Accessories/Banners',
'Accessories/Belts',
'Brand/Brand1',
'Brand/Brand2',
'Apparel/Men/Belts',
'Apparel/Men/Socks',
'Apparel/Women/Leggings'
);
function convert($categories_final) {
$categories = array();
foreach ($categories_final as $cat) {
$levels = explode('/', $cat);
// get category
$category_name = $levels[0];
array_shift($levels);
if(!array_key_exists($category_name,$categories)) {
$categories[$category_name] = array();
}
$tmp = &$categories[$category_name] ;
foreach($levels as $index => $val){
if($index + 1 === count($levels) ){
$tmp[] = $val;
} else {
$i = find_index($tmp , $val);
if( $i == count($tmp) ) { // object not found , we create a new sub array
$tmp[] = array($val => array());
}
$tmp = &$tmp[$i][$val];
}
}
}
return $categories;
}
function find_index($array , $key) {
foreach($array as $i => $val ) {
if(is_array($val) && array_key_exists($key , $val) ){
return $i ;
}
}
return count($array);
}
print_r(convert($source));
這是結果
Array
(
[Accessories] => Array
(
[0] => Apron
[1] => Banners
[2] => Belts
)
[Brand] => Array
(
[0] => Brand1
[1] => Brand2
)
[Apparel] => Array
(
[0] => Array
(
[Men] => Array
(
[0] => Belts
[1] => Socks
)
)
[1] => Array
(
[Women] => Array
(
[0] => Leggings
)
)
)
)

TA貢獻1752條經驗 獲得超4個贊
一種方法是將數組項“轉換”為 json,然后解碼為數組。
我首先執行中間步驟,其中字符串變為無效的 json,然后 preg_replace 使內部變為{}有效[]。
然后與結果合并。
$result =[];
foreach($arr as $val){
$count = count(explode("/", $val));
$str = '{"' . str_replace('/', '":{"', $val) . '"}' . str_repeat("}", $count-1);
$json = preg_replace("/(.*)(\{)(.*?)(\})/", "$1[$3]", $str);
$result = array_merge_recursive($result, json_decode($json, true));
}
Print_r($result);
- 3 回答
- 0 關注
- 180 瀏覽
添加回答
舉報