【发布时间】:2017-04-23 23:17:30
【问题描述】:
我有一个多维数组,它有一个树状结构 parent => child。我想将孩子添加到最后一个数组节点,但我不知道如何。下面我有我的数组和到目前为止的一段代码,我只是卡住了
Array
(
[id] => 154
[text] => root
[parent_id] =>
[children] => Array
(
[155] => Array
(
[id] => 155
[text] => DE
[parent_id] => 154
[children] => Array
(
[157] => Array
(
[id] => 157
[text] => Mülheim
[parent_id] => 155
[children] => Array
(
)
)
[158] => Array
(
[id] => 158
[text] => Heißen
[parent_id] => 155
[children] => Array
(
)
)
[159] => Array
(
[id] => 159
[text] => Essen
[parent_id] => 155
[children] => Array
(
)
)
)
)
[156] => Array
(
[id] => 156
[text] => RO
[parent_id] => 154
[children] => Array
(
[160] => Array
(
[id] => 160
[text] => Alba Iulia
[parent_id] => 156
[children] => Array
(
)
)
[161] => Array
(
[id] => 161
[text] => Sibiu
[parent_id] => 156
[children] => Array
(
)
)
)
)
)
)
这是我的递归遍历函数。任何帮助表示赞赏。谢谢!
function traverseArray($array, &$in_arr = array())
{
foreach($array as $k=>$v)
{
if($k == 'children' && empty($v)){
// here i am querying children data for the end node that has ['children'] => array().
// I did some tests and it seems that no matter what i do here does not affect the $in_array variable at all
$data = Location::all(array('conditions'=>array("parent_id=?", $array['id'])));
// here I try to assign the new childrens to $in_array
foreach ($data as $k=>$v){
$in_arr['children'] = array('href'=>$v->id,'text'=>$v->name);
}
}
else{
$in_arr[] = $v;
}
if(is_array($v))
{
traverseArray($v);
}
}
return $in_arr;
}
【问题讨论】:
标签: php recursion multidimensional-array