PHP数组排序使用内VAL [英] PHP array sort using inner val

查看:189
本文介绍了PHP数组排序使用内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
    )

推荐答案

您可以使用 usort 的与此相比功能:

You can use usort with this comparison function:

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

您也可以使用 在array_multisort 与关键值的排序其它阵列顺序:

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);

下面 array_map 用的匿名函数用于构建的数组的排序的用于数组值本身进行排序的值。这样做的好处是,有NP比较功能需要被称为每对值

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.

这篇关于PHP数组排序使用内VAL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆