This is a discussion on Tree-like structure in PHP? within the PHP General forums, part of the PHP Programming Forums category; I'm trying to use arrays to implement a sort of data tree. For the code to work, it is ...
|
|||||||
| FAQ | Members List | Calendar | Search | Today's Posts | Mark Forums Read |
|
|||
|
I'm trying to use arrays to implement a sort of data tree. For the code to
work, it is essential that the nodes can be edited after they have become part of the tree. That would require that the array elements are pushed "by reference" rather than "by value". <?php $arr1 = array (); $arr2 = array (); array_push ($arr1, 1); array_push ($arr1, $arr2); // <-- the important line array_push ($arr1, 2); array_push ($arr2, 3); array_push ($arr2, 4); // Contents of $arr2 are now empty // apparently $arr2 is inserted by value print_r ($arr1); echo "Expected output:\n"; $arr1[1] = $arr2; print_r ($arr1); ?> What is the most obvious way to implement a tree-like structure in PHP? Is there a way to push arrays by reference rather than by value? BTW: I'm using PHP CLI version 5.2 |
|
|||
|
On 16/11/2007, Paul van Haren <paul.vanharen@zonnet.nl> wrote:
> I'm trying to use arrays to implement a sort of data tree. For the code to > work, it is essential that the nodes can be edited after they have become > part of the tree. That would require that the array elements are pushed > "by reference" rather than "by value". > > <?php > > $arr1 = array (); > $arr2 = array (); > > array_push ($arr1, 1); > array_push ($arr1, $arr2); // <-- the important line array_push ($arr1, &$arr2); or $arr1[] =& $arr2; -robin |
|
|||
|
Paul van Haren wrote:
> I'm trying to use arrays to implement a sort of data tree. For the code to > work, it is essential that the nodes can be edited after they have become > part of the tree. That would require that the array elements are pushed > "by reference" rather than "by value". > > <?php > > $arr1 = array (); > $arr2 = array (); > > array_push ($arr1, 1); > array_push ($arr1, $arr2); // <-- the important line $arr1[] =& $arr2; > array_push ($arr1, 2); > array_push ($arr2, 3); > array_push ($arr2, 4); > > // Contents of $arr2 are now empty > // apparently $arr2 is inserted by value > print_r ($arr1); > > echo "Expected output:\n"; > $arr1[1] = $arr2; > print_r ($arr1); > ?> > > What is the most obvious way to implement a tree-like structure in PHP? Is > there a way to push arrays by reference rather than by value? > > BTW: I'm using PHP CLI version 5.2 > |
|
|||
|
> What is the most obvious way to implement a tree-like structure in PHP?
Use someone elses code that already works. :) Array based tree class is here: http://www.phpguru.org/Tree/Tree.phps -- Richard Heyes +44 (0)800 0213 172 http://www.websupportsolutions.co.uk Knowledge Base and HelpDesk software that can cut the cost of online support |
![]() |
| Thread Tools | |
| Display Modes | |
|
|