Ondrashek Ondrashek - 2 months ago 16
PHP Question

PHP Array Tree in Loop

I need generate Array Tree like:

Array (
[0] => Array (
[parent] => 1
Array( [name] =>name
[lastname] => lastname
Array( [name] =>name
[lastname] => lastname
)
)
Array (
[1] => Array (
[parent] => 1
Array( [name] =>name
[lastname] => lastname
Array( [name] =>name
[lastname] => lastname
)
)


My code is:

foreach($something as $value)
{
$array[] = Array('parent' => $value);
foreach($somethingelse as $valueelse)
{
$array[] = Array('name' => $valueelse, 'lastname' => $valueelse2);
}

}


Output with this code is:

Array (
[0] => Array (
[parent] => 1
[1] => Array( [name] =>name
[lastname] => lastname )
[2] => Array( [name] =>name
[lastname] => lastname )
)
Array (
[0] => Array (
[parent] => 1
[1] => Array( [name] =>name
[lastname] => lastname )
[2] => Array( [name] =>name
[lastname] => lastname )
)


I am building tree for email output and sometimes I got null array in children so my goal is something like:

parent
children
children
parent
children

Answer

You are pushing all the values to the same array

when you write array[] = value it will add the new value at the end of the array.

as per your requirement you have to create subarray first and then add the new array into parent array some thing like this

foreach($something as $value)
 {
      $subArray = Array('parent' => $value);
      foreach($somethingelse as $valueelse)
      {
         $subArray[] = Array('name' => $valueelse, 'lastname' => $valueelse2);
      }

      // your subarray will be array(parent=>1,array('name'=>value....)) and 
      //we dd this sub array into main array.
      $array[] = $subArray;

 }