This problem is somewhat similar to order by in Mysql. What is needed is to simulate the sorting of different fields in the array.
Suppose there is the following array:
$beforeSort = [
"0" => ["name" => "Zhang San", "english" => 80, "chinese" => 60, "math" => 50 ],
"1" => ["name" => "李思", "english" => 50, "chinese" => 60, "math" => 70 ],
"2" => ["name" => "老王", "english" => 30, "chinese" => 50, "math" => 80 ],
];
Now you need to follow the chinese
order in the array. If they are the same, follow the math
order. The final result should be the following array:
$afterSort = [
"2" => ["name" => "老王", "english" => 30, "chinese" => 50, "math" => 80 ],
"0" => ["name" => "Zhang San", "english" => 80, "chinese" => 60, "math" => 50 ],
"1" => ["name" => "李思", "english" => 50, "chinese" => 60, "math" => 70 ],
];
Do you have any different ways to achieve this?
This is the version I use myself. How to use it:
Print results:
You can convert arrays into sets and then process them. The sort method implemented using PHP collections specializes in various complex sorting
<?php
//Now you need to follow the chinese order in the array. If they are the same, follow the math order. The final result should be the following array:
$beforeSort = [
];
$data_math = array_column($beforeSort,'math');
$data_chinese = array_column($beforeSort,'chinese');
array_multisort($data_chinese,SORT_ASC,$data_math,SORT_ASC,$beforeSort);
print_r($beforeSort );
///Borrowing the answer from the guy upstairs
For sorting multi-dimensional arrays, there is an official function that can implement array_multisort
$beforeSort = [
];
foreach ($beforeSort as $key => $value) {
}
array_multisort($chinese, SORT_ASC, $math, SORT_ASC, $beforeSort);
print_r($beforeSort);