up vote 0 down vote favorite

Hey,

i have have got an array of the complexe sort to store my navigation (which is supposed to be changed by the user afterwards). I do not want to have the script only work with 3 levels of depth so I am looking for a nice and good way to sort this array by the position field.

$nav[1]=array(  
  'name'=>'home',  
  'position'=>'2',  
children=>array(

    [1]=array(
    'name'=>'page2',
     position=>'3'),

    [2]=array(
    'name'=>'page3',
    'position'=>'1'),

    [3]=array(
    'name'=>'page4',
    'position'=>'2')
)
$nav[2]=array(
  'name'=>'Second level 1',
  'position'=>'1'
);

I hope someone can help me, thanks for thinking about the problem.

link|flag

2 Answers

up vote 3 down vote accepted

Sort each children array recursively. For example:

function cmp($a, $b)
{
    $ap = intval($a['position']);
    $bp = intval($b['position']);
    if ($ap == $bp) {
        return 0;
    }
    return ($ap < $bp) ? -1 : 1;
}

function sort_menu(&$item)
{
    if ($item['children']) {
        foreach ($item['children'] as &$child) {
            sort_menu($child);
        }
        usort($item['children'], "cmp");
    }
}

$tmp = array('children' => $nav);
sort_menu($tmp);
$nav = $tmp['children'];
link|flag
PHP´s usort function will come in handy: de.php.net/manual/en/function.usort.php – Max Oct 27 '09 at 8:22
up vote 0 down vote

Here is an example of usort.

function yourSortFunction($a, $b)
{
    if ($a['position'] == $b['position']) {
        return 0;
    }
    return ($a['position'] < $b['position']) ? -1 : 1;
}

usort($nav, "yourSortFunction");'

You can call it in your $nav array in recursion in other function.

link|flag
Hey, my problem is, that I do not get the recursion to work with an unknow, potentially infinit number of levels (child of child of child of ...) – Lukas Oppermann Oct 27 '09 at 10:45
Lukáš Lalinský posted correct solution for your problem – Arkadiusz Kondas Oct 27 '09 at 20:06
okey, i will try it again and look into it more closely. thanks. – Lukas Oppermann Oct 28 '09 at 11:19

Your Answer

get an OpenID
or
never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.