xxxxxxxxxx
$keys = array_column($array, 'Price');
array_multisort($keys, SORT_ASC, $array);
print_r($array);
xxxxxxxxxx
$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);
xxxxxxxxxx
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)
xxxxxxxxxx
array_multisort(array_map(function($element) {
return $element['order'];
}, $array), SORT_ASC, $array);
print_r($array);
xxxxxxxxxx
$people= array(
array("age"=>54,"first_name"=>"bob","last_name"=>"Dillion"),
array("age"=>22,"first_name"=>"darah","last_name"=>"Harvard"),
array("age"=>31,"first_name"=>"ahuck","last_name"=>"Bartowski"),
);
echo '<PRE>';
print_r($people);
$keys = array_column($people, 'first_name');
print_r($keys);
array_multisort($keys, SORT_ASC, $people);
print_r($people);
xxxxxxxxxx
usort($myArray, function($a, $b) {
return $a['order'] <=> $b['order'];
});
xxxxxxxxxx
//Products Array
$products = [
[
'id' => 1,
'title' => 'Laptop',
'stock' => 12,
],[
'id' => 2,
'title' => 'Mobile',
'stock' => 30,
],[
'id' => 3,
'title' => 'USB Cable',
'stock' => 5,
],[
'id' => 4,
'title' => 'Power Bank',
'stock' => 53,
],[
'id' => 5,
'title' => 'Mobile Charger',
'stock' => 28,
],
];
//Sort array by stock in descending order
$sorted_products = sort_array_by_key($products, 'stock');
print_r($sorted_products);
//Function to sort array by key
function sort_array_by_key($array, $sort_key){
$key_array = array_column($array, $sort_key);
array_multisort($key_array, SORT_DESC, $array); //or SORT_ASC
return $array;
}
xxxxxxxxxx
function sortByOrder($a, $b) {
return $a['order'] - $b['order'];
}
usort($myArray, 'sortByOrder');
xxxxxxxxxx
//Sorting multidimensional array in php
<?php
$items = [
['item_code' => 'cake', 'name' => 'Cake', 'price' => 150],
['item_code' => 'pizza', 'name' => 'Pizza', 'price' => 250],
['item_code' => 'puff', 'name' => 'Veg. Puff', 'price' => 20],
['item_code' => 'samosa', 'name' => 'Samosa', 'price' => 14]
];
$arr_col = array_column($items, 'name');
print "Before sort: ";
print_r($arr_col);
array_multisort($arr_col,SORT_ASC,$items);
$arr_col = array_column($items, 'name');
print "After sort: ";
print_r($arr_col);
?>
xxxxxxxxxx
usort($data, function($a, $b) {
$rdiff = $a['age'] - $b['age'];
if ($rdiff) return $rdiff;
return $a['sex'] - $b['sex'];
});