简体   繁体   中英

PHP array sort using inner val

Array
(
[1] => Array
    (
        [id] => 1
        [sort] => 1
    )

[3] => Array
    (
        [id] => 3
        [sort] => 3
    )

[2] => Array
    (
        [id] => 2
        [sort] => 2
    )

)

How do i sort it so its re-ordered using the inner 'sort' key ? ie the above would look like this:

Array
(
[1] => Array
    (
        [id] => 1
        [sort] => 1
    )

[2] => Array
    (
        [id] => 2
        [sort] => 2
    )

[3] => Array
    (
        [id] => 3
        [sort] => 3
    )

)

You can use usort with this comparison function:

function cmpBySort($a, $b) {
    return $a['sort'] - $b['sort'];
}
usort($arr, 'cmpBySort');

Or you use array_multisort with an additional array of key values for the sort order:

$keys = array_map(function($val) { return $val['sort']; }, $arr);
array_multisort($keys, $arr);

Here array_map with the anonymous function is used to build an array of the sort values that is used to sort the array values itself. The advantage of this is that there is np comparison function that needs to be called for each pair of values.

像这样的东西:

usort($array, function (array $a, array $b) { return $a["sort"] - $b["sort"]; });

Something like this:

uasort($array, 'compfunc');

function compfunc($a, $b)
{
    return $a['sort'] - $b['sort'];
}

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