我有一个数组,看起来像这样(示例中改为food,它实际上是业务主题标签的分类法(:
Array
(
[fruit] => Fruit
[fruit/apple] => Apple
[fruit/banana] => Banana
[fruit/passion-fruit] => Passion fruit
[vegetable] => Vegetable
[vegetable/beans] => Beans
[vegetable/beans/runner-beans] => Runner beans
)
我想使用递归(大概(将其更改为:
Array
(
[fruit] => Array
(
[title] => Fruit
[children] => Array
(
[apple] => Array
(
[title] => Apple
)
[banana] => Array
(
[title] => Banana
)
[passion-fruit] => Array
(
[title] => Passion fruit
)
)
)
[vegetable] => Array
(
[title] => Vegetable
[children] => Array
(
[beans] => Array
(
[title] => Beans
[children] => Array
(
[runner-beans] => Array
(
[title] => Runner beans
)
)
)
)
)
)
我不知道怎么做。我在这里找到了其他将扁平数组转换为多维数组的例子,但没有找到有值("标题"(和自定义子节点的例子。提前感谢您的指点。
假设您的数组命名为$array
:
$result = array();
foreach($array as $key => $value) {
$temp =& $result;
$path = explode('/', $key);
foreach($path as $subkey) {
if(!isset( $temp[$subkey])) {
$temp[$subkey]['title'] = $value;
$temp[$subkey]['children'] = array();
}
$temp =& $temp[$subkey]['children'];
}
}
即使它创建了一个children
密钥,即使没有孩子,我也会发布它。我将重新访问并编辑。