使用PHP构造这样的阵列的简便方法是什么?
Array
(
[0] => Array
(
[category] => vegetable
[type] => garden
[name] => cabbage
)
[1] => Array
(
[category] => vegetable
[type] => garden
[name] => eggplant
)
[2] => Array
(
[category] => fruit
[type] => citrus
)
)
我目前正在为此解决解决方案。
可能不是“美丽”的方式,而只是这样的东西?
$newArray = array();
foreach($currentArray as $item)
{
if(!empty($item['children']) && is_array($item['children']))
{
foreach($item['children'] as $children)
{
$newArray[] = array( 'category'=>$item['category'] , 'type'=>$item['type'] , 'name'=>$children['name']);
}
}
else
{
$newArray[] = array( 'category'=>$item['category'] , 'type'=>$item['type']);
}
}
children
降低层次结构吗?
<?php
function transform_impl($arr, $obj, &$res) {
$res = array();
foreach ($arr as $item) {
$children = @$item['children'];
unset($item['children']);
$res[] = array_merge($obj, $item);
if ($children) {
transform_impl($children, array_merge($obj, $item), $res);
}
}
}
function transform($arr) {
$res = array();
transform_impl($arr, array(), $res);
return $res;
}
print_r(transform(array(
array("category" => "vegetable", "type" => "garden", "children" =>
array(array("name" => "cabbage"), array("name" => "eggplant"))
),
array("category" => "fruit", "type" => "citrus")
)));
在每个父级上列出。如果没有孩子,请将父级推入结果数组。如果有孩子,请在推入结果阵列之前将家长数据预先到子数据中。 demo