Sort array by multiple fields (closest to number)

How can I sort an array by two (one) different values?

So I have an array like this:

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

The array is already sorted by key total, but they all have the same value in total. So I need to sort who is closest to 3000 on entry.

Edit

The array must first be sorted using total, and then entry, since it is entryonly there, so I can tell who is the best.

So the array should look like this:

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
   )
);
+4
source share
1 answer

Try the following:

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

Conclusion:

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, , entry 3000 entry s.

eval.in

+2

Source: https://habr.com/ru/post/1688602/


All Articles