How to sort associative arrays by value of a given key and maintain key in php? -
this question has answer here:
given array
$inventory = array( "sdfsdfsdsx65fsdf1"=>array("type"=>"fruit", "price"=>3.50), "sdfsdfsdsx65fsdf2"=>array("type"=>"milk", "price"=>2.90), "sdfsdfsdsx65fsdf3"=>array("type"=>"pork", "price"=>5.43) );
i want output below
$inventory = array( "sdfsdfsdsx65fsdf3"=>array("type"=>"pork", "price"=>5.43), "sdfsdfsdsx65fsdf1"=>array("type"=>"fruit", "price"=>3.50), "sdfsdfsdsx65fsdf2"=>array("type"=>"milk", "price"=>2.90) );
$inventory = array( array("sdfsdfsdsx65fsdf1"=>array("type"=>"fruit", "price"=>3.50)), array("sdfsdfsdsx65fsdf2"=>array("type"=>"milk", "price"=>2.90)), array("sdfsdfsdsx65fsdf3"=>array("type"=>"pork", "price"=>5.43)) ); usort($inventory, function($a, $b) { foreach ($a $a); foreach ($b $b); if ($a['price'] == $b['price']) return 0; return ($a['price'] < $b['price']) ? 1 : -1; }); print_r($inventory);
Comments
Post a Comment