简体   繁体   中英

Multidimentional associative array sorting by value

I have the associative array which I need to sort by value:

Array
(
    ['group_1'] => Array
        (
            ['key_1'] => Array
                 (
                      ['field_1'] = 'someval',
                      ['order'] = 2
                 )
            ['key_2'] => Array
                 (
                      ['field_1'] = 'someval',
                      ['order'] = 0
                 )
        )

    ['group_2'] => Array
        (
            ...
        )
)

I am trying to sort each 'group_N' array by 'order' field with usort():

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

foreach ($result_array as $group => $values) {      
        uasort($values, "cmp");         
}

But no success. How can I do it?

Passing arguments by reference as suggested solved the problem.

Working excellently with:

foreach ($result_array as $group => &$values) {      
    uasort($values, "cmp");         
}

to modify an array in a foreach loop, you must pass the key/val by reference like so

foreach ($result_array as &$group => &$values) {      
        uasort($values, "cmp");         
}

or use array walk() (according to @zerkms this is slower, so probably a bad idea)

array_walk($array,
   function(&$row){
       uasort($row, "cmp");
   }
);

demo using array walk

I have the associative array which I need to sort by value:

Array
(
    ['group_1'] => Array
        (
            ['key_1'] => Array
                 (
                      ['field_1'] = 'someval',
                      ['order'] = 2
                 )
            ['key_2'] => Array
                 (
                      ['field_1'] = 'someval',
                      ['order'] = 0
                 )
        )

    ['group_2'] => Array
        (
            ...
        )
)

I am trying to sort each 'group_N' array by 'order' field with usort():

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

foreach ($result_array as $group => $values) {      
        uasort($values, "cmp");         
}

But no success. How can I do it?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM