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 关注
- 145 浏览
添加回答
举报