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:

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
        )
)

Into a nested parent/child array, use this:

$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 '<pre>'; print_r($ret); echo '</pre>';

voila!

Category: PHP 2 comments »

2 Responses to “Building a nested array from a flat one”

  1. Thomas

    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.?

  2. kvz

    If you enjoy this you might like a writeup on a similar technique as well:
    http://kevin.vanzonneveld.net/techblog/article/convert_anything_to_tree_structures_in_php/


Leave a Reply



Back to top