Source array:

$arr = array( array( 'a' => 'a1', 'child' => array()), array( 'a' => 'b1', 'child' => array( array( 'a' => 'b2', 'child' => array()), array( 'a' => 'b3', 'child' => array()) )), array( 'a' => 'c1', 'child' => array( array( 'a' => 'c2', 'child' => array( array( 'a' => 'c3', 'child' => array( array( 'a' => 'c4', 'child' => array()), array( 'a' => 'c5', 'child' => array()) )), array( 'a' => 'c6', 'child' => array()), )), array( 'a' => 'c7', 'child' => array()) )), array( 'a' => 'd1', 'child' => array( array( 'a' => 'd2', 'child' => array()), array( 'a' => 'd3', 'child' => array()) )), array( 'a' => 'e1', 'child' => array( array( 'a' => 'e2', 'child' => array()), array( 'a' => 'e3', 'child' => array()) )) ); 

The nesting of child elements (depth of nesting) can theoretically be infinite (in practice, up to 50-60 pieces). You need to get an array of the form:

 $result = array( array('a1'), array('b1', 'b2'), array('b1', 'b3'), array('c1', 'c2', 'c3', 'c4'), array('c1', 'c2', 'c3', 'c5'), array('c1', 'c2', 'c6'), array('c1', 'c7'), array('d1', 'd2'), array('d1', 'd3'), array('e1', 'e2'), array('e1', 'e3') ); 

Those. to the final child element in the resulting array should be traced all the parent elements.

Came up with something like this, but still not that:

 function make_table($arr, $level) { $level++; $child_out = null; $i = 0; foreach ($arr as $arr_tmp) { $i++; $out_tmp[$i][] = $arr_tmp['a']; if (count($arr_tmp['child']) > 0) { $child_out = make_table($arr_tmp['child'], $level); } if ($child_out != null) { if ($level == 1) { $out_tmp[$i] = array_merge($out_tmp[$i], $child_out); } else { $out_tmp = array_merge($out_tmp, $child_out); } } $child_out = null; } return $out_tmp; } echo "<pre>"; print_r(make_table($arr, 0)); echo "</pre>"; 

I have already broken my head ... Does anyone have any thoughts?

    1 answer 1

    He asked, he answered:

     $table_out = null; function make_table2($arr, $out_tmp) { global $table_out; foreach ($arr as $arr_tmp) { $tmp = null; $tmp[] = $arr_tmp['a']; if (count($arr_tmp['child']) > 0) { make_table2($arr_tmp['child'], array_merge($out_tmp, $tmp)); } else { $table_out[] = array_merge($out_tmp, $tmp); } } return 1; } make_table2($arr, array()); echo "<pre>"; print_r($table_out); echo "</pre>"; 

    Displays:

     Array ( [0] => Array ( [0] => a1 ) [1] => Array ( [0] => b1 [1] => b2 ) [2] => Array ( [0] => b1 [1] => b3 ) [3] => Array ( [0] => c1 [1] => c2 [2] => c3 [3] => c4 ) [4] => Array ( [0] => c1 [1] => c2 [2] => c3 [3] => c5 ) [5] => Array ( [0] => c1 [1] => c2 [2] => c6 ) [6] => Array ( [0] => c1 [1] => c7 ) [7] => Array ( [0] => d1 [1] => d2 ) [8] => Array ( [0] => d1 [1] => d3 ) [9] => Array ( [0] => e1 [1] => e2 ) [10] => Array ( [0] => e1 [1] => e3 ) )