Рассмотрим следующий пример:
$user1 = array('username' => 'test1', 'score' => 2000, 'someotherdata' => 1.0);
$user2 = array('username' => 'test2', 'score' => 4325, 'someotherdata' => 2.0);
$user3 = array('username' => 'test3', 'score' => 624534, 'someotherdata' => 3.0);
$user4 = array('username' => 'test4', 'score' => 564, 'someotherdata' => 1.4);
$user5 = array('username' => 'test5', 'score' => 34256, 'someotherdata' => 1.5);
$user6 = array('username' => 'test6', 'score' => 5476, 'someotherdata' => 1.8);
$arr = array($user1, $user2, $user3, $user4, $user5, $user6);
Как мне правильно отсортировать $arr по полю score в PHP 7? У меня есть рабочий пузырь, который я сделал сам, но есть ли способ использовать встроенные функции PHP 7, чтобы сделать это хорошо, поскольку пузырьковая сортировка довольно дорога (я мог бы сделать быструю сортировку самостоятельно, но прежде чем я это сделаю, я хотел знать если есть способ получше).






с использованием мультисортировки
$user1 = array('username' => 'test1', 'score' => 2000, 'someotherdata' => 1.0);
$user2 = array('username' => 'test2', 'score' => 4325, 'someotherdata' => 2.0);
$user3 = array('username' => 'test3', 'score' => 624534, 'someotherdata' => 3.0);
$user4 = array('username' => 'test4', 'score' => 564, 'someotherdata' => 1.4);
$user5 = array('username' => 'test5', 'score' => 34256, 'someotherdata' => 1.5);
$user6 = array('username' => 'test6', 'score' => 5476, 'someotherdata' => 1.8);
$arr = array($user1, $user2, $user3, $user4, $user5, $user6);
$score = array();
foreach ($arr as $key => $row)
{
$score[$key] = $row['score'];
}
array_multisort($score, SORT_DESC, $arr);
echo "<pre>";
print_r($score);
echo "</pre>";
Можно использовать usort
$user1 = array('username' => 'test1', 'score' => 2000, 'someotherdata' => 1.0);
$user2 = array('username' => 'test2', 'score' => 4325, 'someotherdata' => 2.0);
$user3 = array('username' => 'test3', 'score' => 624534, 'someotherdata' => 3.0);
$user4 = array('username' => 'test4', 'score' => 564, 'someotherdata' => 1.4);
$user5 = array('username' => 'test5', 'score' => 34256, 'someotherdata' => 1.5);
$user6 = array('username' => 'test6', 'score' => 5476, 'someotherdata' => 1.8);
$arr = array($user1, $user2, $user3, $user4, $user5, $user6);
usort($arr, function($a, $b){
return $a['score'] - $b['score'];
});
echo "<pre>";
print_r( $arr );
echo "</pre>";
Это приведет к:
Array
(
[0] => Array
(
[username] => test4
[score] => 564
[someotherdata] => 1.4
)
[1] => Array
(
[username] => test1
[score] => 2000
[someotherdata] => 1
)
[2] => Array
(
[username] => test2
[score] => 4325
[someotherdata] => 2
)
[3] => Array
(
[username] => test6
[score] => 5476
[someotherdata] => 1.8
)
[4] => Array
(
[username] => test5
[score] => 34256
[someotherdata] => 1.5
)
[5] => Array
(
[username] => test3
[score] => 624534
[someotherdata] => 3
)
)
Док: usort ()
В Yii2 / PHP вы можете использовать мультисорт ArrayHelper: yiiframework.com/doc/guide/2.0/en/…