views:

316

answers:

2

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.

+3  A: 

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'];
Lukáš Lalinský
PHP´s usort function will come in handy: http://de.php.net/manual/en/function.usort.php
Max
A: 

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.

Arkadiusz Kondas
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
Lukáš Lalinský posted correct solution for your problem
Arkadiusz Kondas
okey, i will try it again and look into it more closely. thanks.
Lukas Oppermann