gpt4 book ai didi

php - 将数组分解成多维数组(parent->child->sub-child)

转载 作者:行者123 更新时间:2023-12-04 13:13:43 24 4
gpt4 key购买 nike

我有一个数组($categories_final),看起来类似于:

Array
(
[0] => Accessories/Apron
[1] => Accessories/Banners
[2] => Accessories/Belts
[3] => Brand/Brand1
[4] => Brand/Brand2
[5] => Apparel/Men/Belts
[6] => Apparel/Men/Socks
[7] => Apparel/Women/Leggings
)

我试图让它看起来像这样,这样我就可以将它作为我商店的类别结构添加到数据库中:

Array
(
[Accessories] => Array
(
[0] => Apron
[1] => Banners
[2] => Belts
)
[Apparel] => Array
(
[0] => Men => Array
(
[0] => Belts
[1] => Socks
)
[1] => Women => Array
(
[0] => Leggings
)
)

...etc

这是我到目前为止所得到的,但我无法弄清楚如何在 Men/& Women/下添加 child :

$categories = array();
foreach ($categories_final as $cat) {
$levels = explode('/', $cat);
if (isset($categories[$levels[0]])) {
if (!in_array($levels[1], $categories[$levels[0]])) {
$categories[$levels[0]][]= $levels[1];
}
}
else {
$categories[$levels[0]][]= $levels[1];
}
}
print_r($categories);

再一次,我被困在如何将/Belts、/Socks 和/Leggings 添加到它们各自的父项下。

感谢任何帮助,谢谢!

最佳答案

由于可以有无限数量的分支,您可能应该有一个递归解决方案。我尽了最大努力得到了这段代码:

$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

但我想 sleep ,但我的脑袋不工作,所以如果有人能指出要更改的内容,我将不胜感激。我希望这不是什么大问题:)

关于php - 将数组分解成多维数组(parent->child->sub-child),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62251675/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com