3 回答

TA貢獻(xiàn)1773條經(jīng)驗(yàn) 獲得超3個(gè)贊
由于可以有無限數(shù)量的分支,您可能應(yīng)該有一個(gè)遞歸解決方案。我盡了最大努力得到了這段代碼:
$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;
}
它返回這個(gè):
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貢獻(xiàn)1859條經(jīng)驗(yàn) 獲得超6個(gè)贊
此代碼使您能夠創(chuàng)建任意數(shù)量的子分支。
$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));
這是結(jié)果
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貢獻(xiàn)1752條經(jīng)驗(yàn) 獲得超4個(gè)贊
一種方法是將數(shù)組項(xiàng)“轉(zhuǎn)換”為 json,然后解碼為數(shù)組。
我首先執(zhí)行中間步驟,其中字符串變?yōu)闊o效的 json,然后 preg_replace 使內(nèi)部變?yōu)閧}有效[]。
然后與結(jié)果合并。
$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 關(guān)注
- 187 瀏覽
添加回答
舉報(bào)