Welcome to WebmasterWorld Guest from

Forum Moderators: coopster & jatar k

Message Too Old, No Replies

Sorting object array

facebook json data converted to php object, trying to sort results



9:18 am on Jul 4, 2012 (gmt 0)

I'm getting an events json feed from facebook, converting that to an object with php so i can display on my site. But i need to sort the data and i'm stuck, apparently i can use usort() but i'm really confused with how to implement it. The data is being converted to an object with json_decode() i think.

This is the code I've got to retrieve, decode and display the facebook events json data.

$FBpage = file_get_contents('https://graph.facebook.com/demo/events?access_token=17097252363624|vNXbO1MPwpvP56jU625tR2526wU');
$FBdata = json_decode($FBpage);
foreach ($FBdata->data as $events )
$x_sdt = explode("T",$events->start_time);
$x_sd = explode("-",$x_sdt[0]);
if($x_sdt[0] > date("Y-m-d"))
$StatusID = explode("_", $events->id);
echo '<ul class="shows">';
echo '<li class="date">';
echo $x_sd[2]."/".$x_sd[1]."/".$x_sd[0];
echo '</li>';
echo '<li class="title"><a href="'.get_bloginfo('url').'/shows/#'.$events->id.'">'.maxTruncate($events->name, 62).'</a></li>';
echo '</ul>';

If anyone can point me in the right direction to get the results sorting the object contents via the $events->start_time value I'd be greatly appreciative.

- is usort() correct for this situation?
- how to implement (obviously)



4:46 pm on Jul 5, 2012 (gmt 0)

WebmasterWorld Senior Member eelixduppy is a WebmasterWorld Top Contributor of All Time 10+ Year Member

>> is usort correct for this situation

It can be used for sure.

>> how to implement

Here's some pseudo code to get you started:

* Compare function for two FB data objects
* where comparison occurs by date in ASC order
function cmpByDate($a, $b) {

$aUnix = <extract timestamp from $a, convert to Unix ts>
$bUnix = <extra timestamp from $b, convert to Unix ts>

if($aUnix == $bUnix) return 0;

// switch 1 and -1 around if you want descending order
return $aUnix > $bUnix ? 1 : -1;

Then to sort, you'd call the usort method as you suggested:

usort(fbevents, "cmpByDate");


9:37 pm on Aug 10, 2012 (gmt 0)

Hi, thanks for your help dude, I got it working in the end with the below. couldn't have done it without your help, thanks heaps.

function cmpByDate($a, $b)
$aUnix = strtotime($events->start_time);
$bUnix = strtotime($events->start_time);
if($aUnix == $bUnix) return 0;
return $aUnix > $bUnix ? 1 : -1;


Featured Threads

Hot Threads This Week

Hot Threads This Month