Jump to content

Sorting Multidimensional array on date


Drongo_III

Recommended Posts

Hi Guys

 

Bit confused on the best way to approach this so some advice would be welcome.

 

I have a multidimensional array which is created from a twitter and facebook feed combined into a single array.

 

I want to sort the array by date order but I'm not sure of the best way to do this. I have been looking at array_multisort but I can't see how you get that to work without specifying a precise index.

 

An example of the array I am working with is as follows:

 

print_r($socialMediaArray);

Array
(
   [0] => Array
    (
	    [date] => Fri Jan 04 1:35:43
	    [Message] => Brilliant day last thursday - lets do it again
	    [from] => facebook
    )
   [1] => Array
    (
	    [date] => Sat Jan 26 15:40:51
	    [Message] => how do you like my new fb page?
	    [from] => facebook
    )
   [2] => Array
    (
	    [date] => Thu Jan 24 01:38:19
	    [Message] => Some test message from twitter
	    [from] => twitter
    )
   [3] => Array
    (
	    [date] => Mon Jan 21 20:14:33
	    [Message] => @tester here is a message just for you
	    [from] => twitter
    )
   [4] => Array
    (
	    [date] => Sun Dec 16 19:50:33
	    [Message] => some other message #test
	    [from] => twitter
    )

)

Link to comment
https://forums.phpfreaks.com/topic/274600-sorting-multidimensional-array-on-date/
Share on other sites

Two questions so I can get my tired grey matter around this:

 

1) I should convert the date values to unix time stamps?

2) in the example usort function on php manual ( copied below) what is $b? Is this a copy of the original array against which the value $a is compared?

 

function cmp($a, $B)
{
   if ($a == $B) {
    return 0;
   }
   return ($a < $B) ? -1 : 1;
}
$a = array(3, 2, 5, 6, 1);
usort($a, "cmp");

 

But first, store your dates in a format that can be sorted

The usort() function passes $a and $b to the callback function where $a and $b are pairs of elements in the array.

 

If you convert your dates to timestamps then

 

usort($array, 'cmp');

function cmp ($a, $b )
{
return $a['date'] - $b['date'];
}

Thanks very much guys that worked a treat. I was getting massively confused because I thought I have to pass $a and $b and I couldnt quite see how I would make that dynamic - over complicating it clearly!

 

 

 

The usort() function passes $a and $b to the callback function where $a and $b are pairs of elements in the array.

 

If you convert your dates to timestamps then

 

usort($array, 'cmp');

function cmp ($a $b )
{
return $a['date'] - $b['date'];
}

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.