Reputation: 366
I have a parent array called $list
, and when I var_dump($list);
this is the result:
array (size=10)
0 =>
array (size=4)
'id' => string '6' (length=1)
'title' => string 'Title #1' (length=7)
1 =>
array (size=4)
'id' => string '10' (length=2)
'title' => string 'Title x' (length=7)
...
9 =>
array (size=4)
'id' => string '2' (length=1)
'title' => string 'Title y' (length=3)
As you see i have two keys 'id'
and 'title'
.
I want to add another multidimensional array as an third key named 'children'
I am able to get data of 'children'
with my function named GetChildrenById($id);
But i don't know how to add this array as a third key and name the key 'children'
*
I tried to reach every children by foreach loop but i need result as a big array.
How to achieve this?
Upvotes: 0
Views: 1803
Reputation: 89557
You probably need that:
foreach ($list as &$v) {
$v['children'] = GetChildrenById($v['id']);
}
The &
before $v
indicates that $v
is a reference to a $list
item and not a copy. Consequence, when you apply a change to $v
, the $list
item is modified.
But you can also use the array indexes like that:
foreach ($list as $k => $v) {
$list[$k]['children'] = GetChildrenById($v['id']);
}
Upvotes: 2