Re: Recursion: Ugh!

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



This would have been easier if you'd posted the php code to create the
array, as opposed to the output of print_r. I did this:

<?php
$arr = array(
	array(
		'name' => 'food',
		'children' => array(
		array(
			'name' => 'meat',
			'children' => 
			array(
				array('name' => "beef", "children" => NULL),
				array("name" => "pork", "children" => NULL)
			)
		),
		array(
			'name' => 'friut',
			'children' => 
			array(
				array('name' => "pears", "children" => NULL),
				array('name' => "apples", "children" => NULL),
				array('name' => "oranges", "children" => NULL)
			)
		),
		array(
			'name' => 'veg',
			'children' => 
			array(
				array('name' => "parsnips", "children" => NULL),
				array('name' => "carrots", "children" => NULL),
				array('name' => "tomatoes", "children" => NULL),
			)
		)
		)
	)
);

function display_array($arr, $prefix=""){
	while(list($k, $v) = each($arr)){
		if(is_array($ca = $arr[$k]['children'])){
			display_array($ca, $prefix . $arr[$k]['name'] . ":");
		} else {
			echo $prefix . $arr[$k]['name'] . "\n";
			
		}
	}
}			

display_array($arr);

?>

On 5/26/05, Chris W. Parker <cparker@xxxxxxxxxxxx> wrote:
> Marek Kilimajer <mailto:lists@xxxxxxxxxxxxx>
>     on Thursday, May 26, 2005 11:35 AM said:
> 
> > untested:
> >
> > function display($array, $prefix = '') {
> >       echo $prefix ':' . $array['name'] . "\n";
> >       if(is_array($array['children']) && $array['children']) {
> >               foreach($array['children'] as $child) {
> >                       display($child, $prefix ':' . $array['name']);
> >               }
> >       }
> > }
> 
> Thanks Marek.
> 
> I've had one suggestion off list also and, although I haven't been able
> to test this myself, I think my major mistake is that I've been doing
> the foreach() BEFORE checking for the existence of an array. Whereas
> both suggestions so far are checking for the existence of an array
> before the foreach().
> 
> I'll report back to the list with my results. Probably tomorrow.
> 
> 
> Thanks,
> Chris.
> 
> --
> PHP General Mailing List (http://www.php.net/)
> To unsubscribe, visit: http://www.php.net/unsub.php
> 
>

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux