I'm somewhat of a PHP newbie, only doing this as a hobby for the last couple of years.
I have an object of this prototype:
menu_node ->name
->order
->children
where children
may be an array of these same objects - so could go many levels deep. I wrote a simple recursive function that goes through the nesting and executes usort
on each ->children
:
private function sort_node( $node ) {
if ( isset($node->children) ) {
usort( $node->children,
function($a, $b) {return ($a->order == $b->order) ? 0 : ( ($a->order < $b->order) ? -1 : 1 );}
);
foreach ( $node->children as $child_node ) {
$this->sort_node( $child_node );
}
}
return $node;
}
It seems to work fine. But I'm not sure "why" it works fine, which I don't like - I want to know for sure.
I'm worried about what goes on with the passed-in object inside of that foreach
loop - am I consistently modifying the memory space of the passed-in object or am I just lucky that my version and configuration of PHP happens to work ok, but it's really indeterminate as to how it would work across other installations?
I guess I am not sure when to use the argument format &$node
instead of $node
? Same for the iterator variable $child_node
, in that loop.
Any insight or confirmation that what I have here is ok, would be appreciated.