note 89898 added to book.array
| From: | macnimble at gmail dot com | Date: | Fri, 27 Mar 2009 14:59:30 +0000 |
| Subject: | note 89898 added to book.array | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-152521@lists.php.net to get a copy of this message | ||
Converting a linear array (like a mysql record set) into a tree, or multi-dimensional array can be a
real bugbear. Capitalizing on references in PHP, we can 'stack' an array in one pass,
using one loop, like this:
<?php
# array_stack()
# Original idea from:
# http://www.ideashower.com/our_solutions/
# create-a-parent-child-array-structure-in-one-pass/
function array_stack (&$a, $p = '@parent', $c = '@children')
{
$l = $t = array();
foreach ($a AS $key => $val):
if (!$val[$p]) $t[$key] =& $l[$key];
else $l[$val[$p]][$c][$key] =& $l[$key];
$l[$key] = (array)$l[$key] + $val;
endforeach;
return $a = array('tree' => $t, 'leaf' => $l);
}
# Example:
$node = array();
$node[1] = array('@parent' => 0, 'title' => 'I am node 1.');
# ^-----------------------v Link @parent value to key.
$node[2] = array('@parent' => 1, 'title' => 'I am node 2.');
$node[3] = array('@parent' => 2, 'title' => 'I am node 3.');
$node[4] = array('@parent' => 1, 'title' => 'I am node 4.');
$node[5] = array('@parent' => 4, 'title' => 'I am node 5.');
array_stack($node);
$node['leaf'][1]['title'] = 'I am node one.';
$node['leaf'][2]['title'] = 'I am node two.';
$node['leaf'][3]['title'] = 'I am node three.';
$node['leaf'][4]['title'] = 'I am node four.';
$node['leaf'][5]['title'] = 'I am node five.';
echo '<pre>',print_r($node['tree'],TRUE),'</pre>';
?>
Note that there's no parameter checking on the array value, but this is only to keep the
function size small. One could easily a quick check in there to make sure the $a parameter was in
fact an array.
Hope you find it useful. Huge thanks to Nate Weiner of IdeaShower.com for providing the original
function I built on.
----
Server IP: 69.147.83.197
Probable Submitter: 72.192.19.244
----
Manual Page -- http://www.php.net/manual/en/book.array.php
Edit -- https://master.php.net/note/edit/89898
Del: integrated -- https://master.php.net/note/delete/89898/integrated
Del: useless -- https://master.php.net/note/delete/89898/useless
Del: bad code -- https://master.php.net/note/delete/89898/bad+code
Del: spam -- https://master.php.net/note/delete/89898/spam
Del: non-english -- https://master.php.net/note/delete/89898/non-english
Del: in docs -- https://master.php.net/note/delete/89898/in+docs
Del: other reasons-- https://master.php.net/note/delete/89898
Reject -- https://master.php.net/note/reject/89898
Search -- https://master.php.net/manage/user-notes.php