Example 1: php sort array by key
$weight = [
'Pete' => 75,
'Benjamin' => 89,
'Jonathan' => 101
];
ksort($weight);
Example 2: php sort array by specific key
usort($array, function ($a, $b) {
return ($a['specific_key'] < $b['specific_key']) ? -1 : 1;
});
Example 3: 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);
Example 4: php array sort by key value
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).
Example 5: array sort php
$room_details = array(
"2020-09-27": [
{
"content": "how are you",
"detail_id": "1",
"time": "17:57:28",
"chat_time": "2020-09-24 17:57:28",
"width": "0",
"height": "0",
"type": "1",
"distance_time": "26 days ago",
"avatar": "uploads/MemberImage/20200922-1436-image-5f699b536f438-0.png",
"position": 2
},
{
"content": "I am fine, thanks",
"detail_id": "2",
"time": "17:57:45",
"chat_time": "2020-09-24 17:57:45",
"width": "0",
"height": "0",
"type": "1",
"distance_time": "26 days ago",
"avatar": "uploads/MemberImage/20200922-1436-image-5f699b536f438-0.png",
"position": 2
},
],
"2020-09-24": [
{
"content": "how are you",
"detail_id": "1",
"time": "17:57:28",
"chat_time": "2020-09-24 17:57:28",
"width": "0",
"height": "0",
"type": "1",
"distance_time": "26 days ago",
"avatar": "uploads/MemberImage/20200922-1436-image-5f699b536f438-0.png",
"position": 2
},
{
"content": "I am fine, thanks",
"detail_id": "2",
"time": "17:57:45",
"chat_time": "2020-09-24 17:57:45",
"width": "0",
"height": "0",
"type": "1",
"distance_time": "26 days ago",
"avatar": "uploads/MemberImage/20200922-1436-image-5f699b536f438-0.png",
"position": 2
},
],
);
sort($room_details);
$room_details = array(
"2020-09-24": [
...
],
"2020-09-27": [
...
],
);
Example 6: php order array by specific key
function cmp($a, $b)
{
return strcmp($a->display_name, $b->display_name);
}
usort($blogusers, "cmp");
foreach ($blogusers as $bloguser)
{
...