0

This is my code, and I need your help to understand it.

<?php $tree = array(
array(
 'name' => 'Item-1', 
 'children' => array()),
array('name' => 'Item-2', 
 'children' => array(
 array('name' => 'Item-2-1', 
 'children' => array()),
)),
array('name' => 'Item-3', 
 'children' => array(
 array('name' => 'Item-3-1', 
 'children' => array()),
 array('name' => 'Item-3-2', 
 'children' => array(
 array('name' => 'Item-3-2-1', 
 'children' => array()),
 array('name' => 'Item-3-2-2', 
 'children' => array()),
 array('name' => 'Item-3-2-3', 
 'children' => array(
 array('name' => 'Item-3-2-3-1', 
 'children' => array()),
 )),
 )),
)),

);

What i need is one recursive function, which will return all names (name). For example:

Item-1
Item-2
Item-2-1
Item-3
Item-3-1
Item-3-2

........

My attempt but it just doesn't seem to work for me

function tree($tree){ 
 foreach ($tree as $key =>$value) { 
 foreach ($value as $key=>$value){ 
 echo "$value<br>"; } 
 echo "<br>"; } }
hqt
30.4k54 gold badges179 silver badges255 bronze badges
asked Oct 17, 2012 at 22:58
2
  • You need our help in making you understand your own code? Commented Oct 17, 2012 at 23:09
  • I would say that you should first start reading about PHP. You are not having a problem with some code, you look like haven't even tried to do anything. Commented Oct 17, 2012 at 23:09

2 Answers 2

1

You can use RecursiveArrayIterator and RecursiveIteratorIterator

$ai = new RecursiveIteratorIterator(new RecursiveArrayIterator($tree));
echo "<pre>";
foreach ( $ai as $value ) {
 echo $value, PHP_EOL;
}

Output

Item-1
Item-2
Item-2-1
Item-3
Item-3-1
Item-3-2
Item-3-2-1
Item-3-2-2
Item-3-2-3
Item-3-2-3-1

See Live Demo

answered Oct 17, 2012 at 23:04
0

From http://snipplr.com/view/10200/

// Recursively traverses a multi-dimensional array.
function traverseArray($array)
{ 
 // Loops through each element. If element again is array, function is recalled. If not, result is echoed.
 foreach($array as $key=>$value)
 { 
 if(is_array($value))
 { 
 traverseArray($value); 
 }else{
 echo $key." = ".$value."<br />\n"; 
 } 
 }
}

Also see Sum integers in 2d array using recursion?

answered Oct 17, 2012 at 23:04

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.