Building a nested array from a flat one

This post is largely because I want to remember hos to do this, but maybe it’ll be good for someone else out there.

To change an array like this:
[php]
Array (
[0] => Array (
[RECORD_PARENT] => 0
[RECORD_DESC] => Root #1
[RECORD_ID] => 1
[LEVEL] => 1
)
[1] => Array (
[RECORD_PARENT] => 0
[RECORD_DESC] => Root #2
[RECORD_ID] => 2
[LEVEL] => 1
)
[2] => Array (
[RECORD_PARENT] => 0
[RECORD_DESC] => Root #3
[RECORD_ID] => 7
[LEVEL] => 1
)
[3] => Array (
[RECORD_PARENT] => 7
[RECORD_DESC] => Under Root #3
[RECORD_ID] => 8
[LEVEL] => 2
)
)
[/php]

Into a nested parent/child array, use this:

[php]
$ret = array(‘root’=>array());
$ref[0] =& $ret[‘root’];

foreach($retv as $row) {
$p=$row[‘RECORD_PARENT’];
$i=$row[‘RECORD_ID’];

$ref[$p][$i] = array(‘data’=>$row,’ch’=>array());
$ref[$i]=&$ref[$p][$i][‘ch’];
}
echo ‘

'; print_r($ret); echo '

‘;
[/php]

voila!

2 comments

  1. Your example is hard as hell to read (everything has a “magic” e.g. hazy name), but I see what you’re getting at. Do you think you could rephrase this as something clearer, such as nesting animals based on taxonomy, football teams based on divisions, etc.?

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>