php sort multi dimensional array by value

This post explains how to php sort multi dimensional array by value.

$books = array(
array(“type”=>”maths”, “price”=>13.50),
array(“type”=>”science”, “price”=>21.99),
array(“type”=>”social”, “price”=>15.75),
);

$books = sortMultiArrayByValue($inventory, ‘price’,’desc’);
echo “<pre>”;
print_r($books );

function sortMultiArrayByValue($array, $value, $sort_order = ‘asc’){
$sortarray = array();
if(is_array($array)){
foreach ($array as $key => $row){
$sortarray[$key] = $row[$value];
}
if(strtolower(trim($sort_order)) == ‘asc’){
array_multisort($sortarray, SORT_ASC, $array);
}else{
array_multisort($sortarray, SORT_DESC, $array);
}
}
return $array;
}

 

Output:

Array
(
[0] => Array
(
[type] => science
[price] => 21.99
)

[1] => Array
(
[type] => social
[price] => 15.75
)

[2] => Array
(
[type] => maths
[price] => 13.5
)

)

 

Leave a Reply

Your email address will not be published. Required fields are marked *