按多个字段排序数组(最接近数字)

时间:2017-11-02 14:13:47

标签: php arrays sorting

如何按两(1)个不同的值对数组进行排序?

所以我有一个像这样的数组:

array(
   array(
      'id' => 10,
      'total' => 38,
      'entry' => 400
   ),
   array(
      'id' => 4,
      'total' => 34,
      'entry' => 3100
   ),
   array(
      'id' => 2,
      'total' => 34,
      'entry' => 3150
   ),
   array(
      'id' => 8,
      'total' => 34,
      'entry' => 2980
   ),
);

数组已按键total排序,但它们在total中的值都相同。所以我需要按entry排序最接近3000的人。

修改

首先应该按total然后entry对数组进行排序,因为entry只是在那里,所以我可以区分谁是最好的。

所以数组应如下所示:

array(
  array(
      'id' => 10,
      'total' => 38,
      'entry' => 400
  ),
  array(
      'id' => 8,
      'total' => 34,
      'entry' => 2980
   ),
   array(
      'id' => 4,
      'total' => 34,
      'entry' => 3100
   ),
   array(
      'id' => 2,
      'total' => 34,
      'entry' => 3150
   )
);

1 个答案:

答案 0 :(得分:2)

试试这个:

usort($arr, function ($a, $b) {
    if ($a['total'] == $b['total']) { // Only compare on entry when the totals are the same.
        return abs($a['entry'] - 3000) > abs($b['entry'] - 3000);
    }
    return $a['total'] < $b['total'];
});

print_r($arr);

输出:

Array
(
    [0] => Array
        (
            [id] => 2
            [total] => 35
            [entry] => 3150
        )

    [1] => Array
        (
            [id] => 8
            [total] => 34
            [entry] => 2980
        )

    [2] => Array
        (
            [id] => 4
            [total] => 34
            [entry] => 3100
        )

    [3] => Array
        (
            [id] => 6
            [total] => 34
            [entry] => 3250
        )

    [4] => Array
        (
            [id] => 3
            [total] => 32
            [entry] => 3400
        )

)

以下是它的工作原理:它会比较total s,但如果它们相同,则会比较entryentry之间的差值的绝对值

eval.in demo