1function sortByAge($a, $b) {
2 return $a['age'] > $b['age'];
3}
4$people=[
5 ["age"=>54,"first_name"=>"Bob","last_name"=>"Dillion"],
6 ["age"=>22,"first_name"=>"Sarah","last_name"=>"Harvard"],
7 ["age"=>31,"first_name"=>"Chuck","last_name"=>"Bartowski"]
8];
9
10usort($people, 'sortByAge'); //$people is now sorted by age (ascending)
1array_multisort(array_map(function($element) {
2 return $element['order'];
3 }, $array), SORT_ASC, $array);
4
5print_r($array);
1 $keys = array_column($array, 'Price');
2
3 array_multisort($keys, SORT_ASC, $array);
4
5 print_r($array);
1$inventory = array(
2 array("type"=>"Fruit", "price"=>3.50),
3 array("type"=>"milk", "price"=>2.90),
4 array("type"=>"Pork", "price"=>5.43),
5);
6
7$prices = array_column($inventory, 'price');
8$inventory_prices = array_multisort($prices, SORT_DESC, $inventory);
9
10$types = array_map(strtolower, array_column($inventory, 'type'));
11$inventory_types = array_multisort($types, SORT_ASC, $inventory);
1<?php
2function sortByPrice($a, $b){
3 return $a['price'] > $b['price'];
4}
5
6$items = [
7 ['label' => 'cake', 'name' => 'Cake', 'price' => 150],
8 ['label' => 'pizza', 'name' => 'Pizza', 'price' => 250],
9 ['label' => 'puff', 'name' => 'Veg Puff', 'price' => 20],
10 ['label' => 'samosa', 'name' => 'Samosa', 'price' => 14]
11];
12
13//Sort by Price
14usort($items, 'sortByPrice');
15//print_r($items);
16
17print "<br/> After Sort by Price printing: <br/>";
18foreach($items as $item){
19 print $item['name']." ".$item['price']."<br/>";
20}
21$newArray = array_column($items, 'price', 'name');
22
23// find max, min, and toal sum of array
24$totalExp = array_sum(array_column($items, 'price', 'name'));
25$maxPrice = max(array_column($items, 'price', 'name'));
26$minPrice = min(array_column($items, 'price', 'name'));
27
28print "Total Expenses : ".$totalExp."<br/>";
29print "What is Costly Item : ".$maxPrice.' ('.array_search($maxPrice, $newArray).")<br/>";
30print "What is Cheap Item : ".$minPrice.' ('.array_search($minPrice, $newArray).")<br/>";
31
32?>
1function buildSorter($key) {
2 return function ($a, $b) use ($key) {
3 return strnatcmp($a[$key], $b[$key]);
4 };
5}
6
7usort($array, buildSorter('key_b'));