Reputation: 65
How can I sort the below array by any of the child values (i.e: post_id, username, etc...)?
Array(
[0] => Array
(
[id] => 10
[post_id] => 398
[user_id] => 0
[view_date] => 2010-11-20 15:26:00
[views] => 4
[username] => <em>guest</em>
)
[1] => Array
(
[id] => 9
[post_id] => 397
[user_id] => 1
[view_date] => 2010-11-19 23:35:39
[views] => 1
[username] => Fire G
)
[2] => Array
(
[id] => 8
[post_id] => 398
[user_id] => 1
[view_date] => 2010-11-19 23:35:26
[views] => 4
[username] => Fire G
)
[3] => Array
(
[id] => 7
[post_id] => 396
[user_id] => 1
[view_date] => 2010-11-19 23:07:57
[views] => 3
[username] => Fire G
)
[4] => Array
(
[id] => 6
[post_id] => 396
[user_id] => 1
[view_date] => 2010-11-19 23:07:55
[views] => 3
[username] => Fire G
)
[5] => Array
(
[id] => 5
[post_id] => 396
[user_id] => 1
[view_date] => 2010-11-19 23:07:52
[views] => 3
[username] => Fire G
)
[6] => Array
(
[id] => 4
[post_id] => 13
[user_id] => 1
[view_date] => 2010-11-19 22:59:35
[views] => 1
[username] => Fire G
)
[7] => Array
(
[id] => 3
[post_id] => 3
[user_id] => 1
[view_date] => 2010-11-19 22:59:28
[views] => 1
[username] => Fire G
)
[8] => Array
(
[id] => 2
[post_id] => 398
[user_id] => 1
[view_date] => 2010-11-18 11:37:20
[views] => 4
[username] => Fire G
)
[9] => Array
(
[id] => 1
[post_id] => 398
[user_id] => 1
[view_date] => 2010-11-18 11:37:16
[views] => 4
[username] => Fire G
)
)
Upvotes: 4
Views: 3574
Reputation: 52372
Use uasort
, user-defined sorting that lets you provide your own function to define whether one element should come before another.
http://www.php.net/manual/en/function.uasort.php
Your comparator function would be something like
function cmp($a, $b) {
return $a['post_id'] > $b['post_id'] ? 1 : -1;
}
Upvotes: 6