xxxxxxxxxx
$inventory = array(
array("type"=>"fruit", "price"=>3.50),
array("type"=>"milk", "price"=>2.90),
array("type"=>"pork", "price"=>5.43),
);
$price = array_column($inventory, 'price');
array_multisort($price, SORT_DESC, $inventory);
xxxxxxxxxx
$weight = [
'Pete' => 75,
'Benjamin' => 89,
'Jonathan' => 101
];
ksort($weight);
xxxxxxxxxx
$inventory = [
['price' => 10.99, 'product' => 'foo 1'],
['price' => 5.99, 'product' => 'foo 2'],
['price' => 100, 'product' => 'foo 3'],
];
$price = array_column($inventory, 'price');
array_multisort($price, SORT_DESC, $inventory);
xxxxxxxxxx
$array = array(
"name" => "John",
"age" => 30,
"city" => "New York"
);
ksort($array); // Sorts the array by keys in ascending order
print_r($array);
xxxxxxxxxx
usort($array, function ($a, $b) {
return ($a['specific_key'] < $b['specific_key']) ? -1 : 1;
});
xxxxxxxxxx
To PHP sort array by key, you should use:
ksort() (for ascending order) or krsort() (for descending order).
To PHP sort array by value, you will need functions:
asort() and arsort() (for ascending and descending orders).
xxxxxxxxxx
$price = array_column($inventory, 'price'); //price is a key for the sort
array_multisort($price, SORT_DESC, $inventory);
xxxxxxxxxx
//Laravel example
$products = collect($products)->sortBy('name')->toArray();
xxxxxxxxxx
function cmp($a, $b)
{
return strcmp($a->display_name, $b->display_name);
}
usort($blogusers, "cmp");
foreach ($blogusers as $bloguser)
{