php sort multidimensional array by value
function sortByAge($a, $b) {
return $a['age'] > $b['age'];
}
$people=[
["age"=>54,"first_name"=>"Bob","last_name"=>"Dillion"],
["age"=>22,"first_name"=>"Sarah","last_name"=>"Harvard"],
["age"=>31,"first_name"=>"Chuck","last_name"=>"Bartowski"]
];
usort($people, 'sortByAge'); //$people is now sorted by age (ascending)
3.67
3
array_multisort(array_map(function($element) {
return $element['order'];
}, $array), SORT_ASC, $array);
print_r($array);
Thank you!
3
0
4
7
function sortByOrder($a, $b) {
return $a['order'] - $b['order'];
}
usort($myArray, 'sortByOrder');
Thank you!
7
0
4.25
4
$inventory = array(
array("type"=>"Fruit", "price"=>3.50),
array("type"=>"milk", "price"=>2.90),
array("type"=>"Pork", "price"=>5.43),
);
$prices = array_column($inventory, 'price');
$inventory_prices = array_multisort($prices, SORT_DESC, $inventory);
$types = array_map(strtolower, array_column($inventory, 'type'));
$inventory_types = array_multisort($types, SORT_ASC, $inventory);
Thank you!
4
0
4.25
8
usort($myArray, function($a, $b) {
return $a['order'] <=> $b['order'];
});
Thank you!
8
0
3.8
5
$keys = array_column($array, 'Price');
array_multisort($keys, SORT_ASC, $array);
print_r($array);
Thank you!
5
0
Are there any code examples left?
New code examples in category PHP