CodeIgniter Forums
Recurrent function over multidimensional array - arrgh! - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Archived Discussions (https://forum.codeigniter.com/forumdisplay.php?fid=20)
+--- Forum: Archived Development & Programming (https://forum.codeigniter.com/forumdisplay.php?fid=23)
+--- Thread: Recurrent function over multidimensional array - arrgh! (/showthread.php?tid=30099)



Recurrent function over multidimensional array - arrgh! - El Forum - 05-03-2010

[eluser]JoostV[/eluser]
Help! I've busting my head over this one...

I have a multidimensional array of pages. Some pages have no children, but some do (they are in an index 'children'). Then again, some have no children at all. Some kind of recurrent function would probably do the trick, but I keep running round in circles. Help me out, please! Smile

Here's a simplified example
Code:
$pages = array();
$pages[63]['pag_id'] = 63;
$pages[63]['children'][2]['pag_id'] = 2;
$pages[63]['children'][14]['pag_id'] = 14;
$pages[54]['pag_id'] = 54;
$pages[54]['children'][17]['pag_id'] = 17;
$pages[54]['children'][17]['children'][68]['pag_id'] = 68;
$pages[54]['children'][17]['children'][32]['pag_id'] = 32;
$pages[23]['pag_id'] = 23;

I need to run through this array and for each page add a link to the first, deepest child of that page. Or to itself, if it has no children.

After processing, the above array should look like
Code:
$pages = array();
$pages[63]['pag_id'] = 63;
$pages[63]['href'] = 'pages/2';
$pages[63]['children'][2]['pag_id'] = 2;
$pages[63]['children'][2]['href'] = 'pages/2';
$pages[63]['children'][14]['pag_id'] = 14;
$pages[63]['children'][14]['href'] = 'pages/14';
$pages[54]['pag_id'] = 54;
$pages[54]['href'] = 'pages/68';
$pages[54]['children'][17]['pag_id'] = 17;
$pages[54]['children'][17]['href'] = 'pages/68';
$pages[54]['children'][17]['children'][68]['pag_id'] = 68;
$pages[54]['children'][17]['children'][68]['href'] = 'pages/68';
$pages[54]['children'][17]['children'][32]['pag_id'] = 32;
$pages[54]['children'][17]['children'][32]['href'] = 'pages/32';
$pages[23]['pag_id'] = 23;
$pages[23]['href'] = 'pages/23';

*EDIT: corrected error in second array*