开发者

PHP / JSON: Sort two different timestamp formats in one array

I have a merged array from the JSON output of a Facebook and Twitter stream and I want to sort those two into one but they offer two different timestamps:

Facebook: [created_time] => 1299839651 Twitter: [created_at] => Mon Mar 07 16:33:49 +0000 2011

Currently the output contains the full JSON content from both platforms beginning with Array ( [data] => Array ( [0] => Array ( [id] => (Facebook) and ending with [id_str] => 12345678964508161 ) ) (Twitter). In the middle part it looks like this: &limit=25&until=0 ) [0] => Array ( [text] => (Facebook -> Twitter). I am not sure how to handle this. Thanks for help开发者_运维知识库.


You can use strtotime() to convert the Twitter timestamp into one that looks more like the Facebook timestamp.

Then you simply order them based on the numerical timestamp


This should work, assuming I understood your problem correctly.

<?php

// assume $array is your array of associative arrays with created_time 
// being facebook timestamps, created_at being twitter


// takes as arguments two associative arrays with
// created_time keys to compare
function sort_by_created_time($arr1, $arr2)
{
    if ($arr1['created_time'] == $arr2['created_time'])
    {
        return 0;
    }
    elseif ($arr1['created_time'] > $arr2['created_time'])
    {
        return 1;
    }
    else
    {
        return -1;
    }
}

// go through each array, generate timestamps if needed
foreach ($array as &$row)
{
    if (!isset($row['created_time']))
    {
        // convert date formats to timestamps if we need to
        $row['created_time'] = strtotime($row['created_at']);
    }
}
unset($row);

usort($array, "sort_by_created_time");
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜