使用元素内的多个键排序数组元素 - PHP

时间:2016-02-19 11:39:24

标签: php arrays json sorting

我有和数组转换为JSON,如下所示:

[
    {
        "name": "Sally",
        "nick_name": "sal",
        "availability": "0",
        "is_fav": "0"
    },
    {
        "name": "David",
        "nick_name": "dav07",
        "availability": "0",
        "is_fav": "1"
    },
    {
        "name": "Zen",
        "nick_name": "zen",
        "availability": "1",
        "is_fav": "0"
    },
    {
        "name": "Jackson",
        "nick_name": "jack",
        "availability": "1",
        "is_fav": "1"
    },
    {
        "name": "Rohit",
        "nick_name": "rod",
        "availability": "0",
        "is_fav": "0"
    },

]

我想根据is_favavailabilitynick_name的值按以下顺序对整个数组进行排序:

[ is_fav:1 availability:1 ]
[ is_fav:1 availability:0 ]
[ is_fav:0 availability:1 ]
[ is_fav:0 availability:0 ]

在每个条件中,使用nick_name

按字母顺序排列元素

所以上面例子中的最后一个数组看起来像

[
    {
        "name": "Jackson",
        "nick_name": "jack",
        "availability": "1",
        "is_fav": "1"
    },
    {
        "name": "David",
        "nick_name": "dav07",
        "availability": "0",
        "is_fav": "1"
    },
    {
        "name": "Zen",
        "nick_name": "zen",
        "availability": "1",
        "is_fav": "0"
    },
    {
        "name": "Rohit",
        "nick_name": "rod",
        "availability": "0",
        "is_fav": "0"
    },
    {
        "name": "Sally",
        "nick_name": "sal",
        "availability": "0",
        "is_fav": "0"
    },
]

3 个答案:

答案 0 :(得分:1)

试试这个array_multisort

$arr = json_decode($data, true);
// Obtain a list of columns
foreach ($arr as $key => $row) {
    $isFav[$key] = $row['is_fav'];
    $avail[$key] = $row['availability'];
    $names[$key] = $row['nick_name'];
}

// Sort the data with isFav descending, avail descending
// Add $arr as the last parameter, to sort by the common key
array_multisort($isFav, SORT_DESC, $avail, SORT_DESC, $names, SORT_ASC, $arr);

您可以在行动here (3v4l.org)

中看到它

答案 1 :(得分:1)

您可以使用PHP的usort功能,如

usort($arr,function($a,$b){
    $c = $b['is_fav'] - $a['is_fav'];
    $c .= $b['availability'] - $a['availability'];
    $c .= strcmp($a['nick_name'],$b['nick_name']);
    return $c;
});
print_r($arr);

答案 2 :(得分:-1)

$arr = json_decode($data, true);
usort($arr, function ($item1, $item2) {
    // your condition
    if ($item1['is_fav'] && !$item2['is_fav']) return 1;
    if (!$item1['is_fav'] && $item2['is_fav']) return -1;
    if ($item1['availability'] > $item2['availability']) return 1;
    if ($item1['availability'] < $item2['availability']) return -1;
    return 0;
});
$data = json_encode($arr);