Forum Moderators: coopster

Message Too Old, No Replies

Sorting an array by a subarray value

         

asantos

12:59 am on Jan 23, 2009 (gmt 0)

10+ Year Member



I have this array:


[0] => Array
(
[date] => 1300200300
[msg] => Hello!
)

[1] => Array
(
[date] => 1400300400
[msg] => This is cool!
)

[2] => Array
(
[date] => 1200100200
[msg] => No way man!
)

I need the first level array to be ordered by the date value that is in the second level of those arrays.

The final order should be (keys): 2, 0, 1.

Is this feasible? I didnt find any functions or information.

Thanks.

bkeep

5:17 am on Jan 23, 2009 (gmt 0)

10+ Year Member



[us.php.net...] looks like this should do the trick but I can't give you an example as I have never had to use that

tomda

5:46 am on Jan 23, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



It would easier if you can output your array this way
[0] => Array 
(
[1300200300] => Hello!
)

[1] => Array
(
[1400300400] => This is cool!
)

[2] => Array
(
[1200100200] => No way man!
)

The key of your array being the date (as long as each dates are unique). They sorting your array by key is much easier (I think)

coopster

2:55 pm on Jan 23, 2009 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



Here are a couple of multi-dimensional array sorting [webmasterworld.com] options you might consider.

asantos

6:07 pm on Jan 23, 2009 (gmt 0)

10+ Year Member



Thanks, problem solved!

@bkeep: i investigate a little further about this usort function, and it works great!

@tomda: i cant, there are more items in the subarrays... i just used 2 for this example ;)

@coopster: thank you, that link actually contained the cmp() function i use with the usort() function that bkeep suggested.

Final code:

# Order array by date
function cmp($a,$b) {
if ($a['date'] == $b['date']) return 0;
return ($a['date'] < $b['date'])? -1 : 1;
}

usort($inbox,'cmp');
$inbox = array_reverse($inbox);
print_r($inbox);