V
V
vlaabra2014-11-12 14:05:44
PHP
vlaabra, 2014-11-12 14:05:44

How to sort multidimensional associative array by only one value?

Hello.
Here is the array:

$test = [
  [
    'date' => '1',
    'message' => 'Первый'
  ],
  [
    'date' => '3',
    'message' => '1 Третий'
  ],
  [
    'date' => '2',
    'message' => 'Второй'
  ],
  [
    'date' => '3',
    'message' => '0 Четвертый'
  ],
  [
    'date' => '0',
    'message' => 'Нулевой'
  ]
];

Should become like this:
$test = [
  [
    'date' => '0',
    'message' => 'Нулевой'
  ],
  [
    'date' => '1',
    'message' => 'Первый'
  ],
  [
    'date' => '2',
    'message' => 'Второй'
  ],
  [
    'date' => '3',
    'message' => '1 Третий'
  ],
  [
    'date' => '3',
    'message' => '0 Четвертый'
  ]
];

The array_multisort($test) solution sorts by message as well, which is not necessary:
$test = [
  [
    'date' => '0',
    'message' => 'Нулевой'
  ],
  [
    'date' => '1',
    'message' => 'Первый'
  ],
  [
    'date' => '2',
    'message' => 'Второй'
  ],
[
    'date' => '3',
    'message' => '0 Четвертый'
  ],
  [
    'date' => '3',
    'message' => '1 Третий'
  ]
];

This is how it sorts correctly, but much slower:
function cmp($a, $b) {
  $a = $a['date'];
  $b = $b['date'];
  if ($a == $b) {
    return 0;
  }
  return ($a < $b) ? -1 : 1;
}
uasort($test, 'cmp');

Solutions with overwriting values ​​into keys and processing via ksort() are also fast, but lose arrays with the same values.
I would like something as simple and fast as array_multisort() , but to sort by only one value.
Thank you.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey, 2014-11-12
Protko @Fesor

uasort is fast enough. Only the code can be simplified:

uasort($test, function ($a, $b) {
    // если бы у вас там были именно числа...
    // return $a['date'] - $b['date'];
    return strcmp($a['date'], $b['date']);
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question