Wednesday 6 February 2019

Array sorting by key value in php



I would like to sort below array based on amount but I don't know how. Anyone help me



Array(
[0] => Array
(
[id] => 1

[amount] => 20
)
[1] => Array
(
[id] => 2
[amount] => 30
)
[2] => Array
(
[id] => 3

[amount] => 10
)
)

Answer



Use usort.



E.g



function sortByAmount($x, $y) {

return $x['amount'] - $y['amount'];
}

usort($array, 'sortByAmount');
echo "
"; print_r($array);

No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...