views:

35

answers:

2

Okay, a before;

Array (
    'home' => array('order' => 1),
    'about' => array(),
    'folio' => array('order' => 2),
    'folio/web' => array('order' => 2),
    'folio/print' => array('order' => 1)
    'contact' => array('order' => 2)
)

And a desired after;

Array (
    'home' => array('order' => 1),
    'contact' => array('order' => 2),
    'folio' => array('order' => 2),
    'folio/print' => array('order' => 1),
    'folio/web' => array('order' => 2),
    'about' => array()
)

I know, horrific (don't ask!)

See how the slash in the key indicates children, and how the order is nested accordingly? And items without orders are simply shifted to the bottom.

But also how multiple 'same level' items with the same order are merely sorted by key?

+1  A: 

Have you taken a look at http://www.php.net/manual/en/function.asort.php and http://www.php.net/manual/en/function.sort.php

Also whilst looking at sort make sure you check out the flags.

That array may cause alot of issues and i would suggest you change it around to something like

'home' => array(
    'meta' => array('order' => 1)
 ),
'folio' => array(
    'meta' => array('order' => 2),
    'children' => array(
        'print' => array(
             'meta' => array('order' => 1)
              /*Other Children*/
         ),
        'web' => array(
              'meta' => array('order' => 2)
         )
     )
 ),

and try do something a little recursively.

function show_menu(&$return,$array)
{
    $return .= '<ul>';
    foreach($array as $name => $inner)
    {
       $return .= '<li>' . $name
       if(isset($inner['children']))
       {
           show_menu(&$return,$inner['children']);
       }
       $return .= '</li>';
    }
    $return .= '</ul>';
}

$menu = '';
show_menu(&$menu,$menu_array);

echo $menu;

Should create you a nice hierarchy menu, hope this helps.

RobertPitt
Cheers for the response Robert - I do agree with your proposed hierarchy, but I'm currently weighing a trade-off by making other operations harder. I'm gonna have a ponder and perhaps re-evaluate my approach!
TheDeadMedic
That would be the best choice Medic, the beauty of coming across these problems throughout your applications is that you can learn from your mistakes.. the next time you build your application you will take the hierarchy approach to make your life easier.
RobertPitt
+1  A: 

Damn, almost worth to get a bubblesort algorithm and skip all sorting functions altogether. However: if you do one loop:

foreach($array as $idx => $ar){
    $array[$idx]['key'] = $idx;
}

... I see no reason that it couldn't be implemented with uasort(), albeit dirty work...

function somesorter($a,$b){
    //check 'keys' entry in $a & $b first for slash, act accordingly if clear
    //check absence or 'order' entry in one or both
    //compare order entry
}
Wrikken