Answers for "how to sort an array of associative arrays by value of a given key in php"

PHP
1

sort array by key value in php

$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);
Posted by: Guest on June-03-2021
3

php sort by associative array value

//php 7+
usort($inventory, function ($item1, $item2) {
    return $item1['price'] <=> $item2['price'];
});
Posted by: Guest on February-02-2021
2

php sort array of array by key

$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);
Posted by: Guest on August-25-2020
0

sort array php by key

$price = array_column($inventory, 'price'); //price is a key for the sort
array_multisort($price, SORT_DESC, $inventory);
Posted by: Guest on August-31-2021

Code answers related to "how to sort an array of associative arrays by value of a given key in php"

Browse Popular Code Answers by Language