Jump to content

[SOLVED] Problem with recursively get out tree


kustov

Recommended Posts

I have a such array:

$tree= array(
0=>array('id'=>1, 'parent'=>0),
1=>array('id'=>2, 'parent'=>0),
2=>array('id'=>3, 'parent'=>2),
3=>array('id'=>4, 'parent'=>3),
4=>array('id'=>5, 'parent'=>2),
5=>array('id'=>6, 'parent'=>0),
6=>array('id'=>7, 'parent'=>3),
7=>array('id'=>8, 'parent'=>4),
8=>array('id'=>9, 'parent'=>1),
9=>array('id'=>10, 'parent'=>0),
10=>array('id'=>11, 'parent'=>10),
);

and need to get this output:

-1

--9

-2

--3

---4

----8

--5

--7

-6

-10

--11

But I'm very bad in recursion, please help !

Im a little confused with the ordering of your output. I would have thought you would want to group by the parent number?

 

<?php
$tree= array(
0=>array('id'=>1, 'parent'=>0),
1=>array('id'=>2, 'parent'=>0),
2=>array('id'=>3, 'parent'=>2),
3=>array('id'=>4, 'parent'=>3),
4=>array('id'=>5, 'parent'=>2),
5=>array('id'=>6, 'parent'=>0),
6=>array('id'=>7, 'parent'=>3),
7=>array('id'=>8, 'parent'=>4),
8=>array('id'=>9, 'parent'=>1),
9=>array('id'=>10, 'parent'=>0),
10=>array('id'=>11, 'parent'=>10),
);
$new_array = array();
foreach($tree as $value){
$new_array[$value['parent']][] = $value['id'];
}
ksort($new_array);
echo '<pre>';
print_r($new_array);
echo '</pre>'
?>

 

Produces:

 

Array
(
    [0] => Array
        (
            [0] => 1
            [1] => 2
            [2] => 6
            [3] => 10
        )

    [1] => Array
        (
            [0] => 9
        )

    [2] => Array
        (
            [0] => 3
            [1] => 5
        )

    [3] => Array
        (
            [0] => 4
            [1] => 7
        )

    [4] => Array
        (
            [0] => 8
        )

    [10] => Array
        (
            [0] => 11
        )

try

<?php
$tree= array(
0=>array('id'=>1, 'parent'=>0),
1=>array('id'=>2, 'parent'=>0),
2=>array('id'=>3, 'parent'=>2),
3=>array('id'=>4, 'parent'=>3),
4=>array('id'=>5, 'parent'=>2),
5=>array('id'=>6, 'parent'=>0),
6=>array('id'=>7, 'parent'=>3),
7=>array('id'=>8, 'parent'=>4),
8=>array('id'=>9, 'parent'=>1),
9=>array('id'=>10, 'parent'=>0),
10=>array('id'=>11, 'parent'=>10),
);


function my_tree($tree, $start = 0, $r = 0, $first_loop = true) {
if ($first_loop) { //reorganize the array
	$tmp=array();
	foreach ($tree as $a) $tmp[$a['parent']][] = $a['id'];
	$tree = $tmp;
} else $out = "\n".'-'.str_repeat('-',$r++).$start.'<br />';
if (isset($tree[$start])){
	if (is_array($tree[$start])) {
		foreach ($tree[$start] as $v){
			$out .= my_tree($tree, $v, $r, false);
		}
	}
}
return $out;
}

echo my_tree($tree);

?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.