sort array on the basis of key value multidimensional php code example
Example 1: php sort multidimensional array
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');
Example 2: php sort multidimensional array
array_multisort(array_map(function($element) {
return $element['order'];
}, $array), SORT_ASC, $array);
print_r($array);
Example 3: sort multidimensional array in php
<?php
function sortByPrice($a, $b){
return $a['price'] > $b['price'];
}
$items = [
['label' => 'cake', 'name' => 'Cake', 'price' => 150],
['label' => 'pizza', 'name' => 'Pizza', 'price' => 250],
['label' => 'puff', 'name' => 'Veg Puff', 'price' => 20],
['label' => 'samosa', 'name' => 'Samosa', 'price' => 14]
];
usort($items, 'sortByPrice');
print "<br/> After Sort by Price printing: <br/>";
foreach($items as $item){
print $item['name']." ".$item['price']."<br/>";
}
$newArray = array_column($items, 'price', 'name');
$totalExp = array_sum(array_column($items, 'price', 'name'));
$maxPrice = max(array_column($items, 'price', 'name'));
$minPrice = min(array_column($items, 'price', 'name'));
print "Total Expenses : ".$totalExp."<br/>";
print "What is Costly Item : ".$maxPrice.' ('.array_search($maxPrice, $newArray).")<br/>";
print "What is Cheap Item : ".$minPrice.' ('.array_search($minPrice, $newArray).")<br/>";
?>