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!
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.?
LikeLike
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/
LikeLike