phparrayssortingarray-merge

How to combine Twitter and Facebook Post and Sort them by Time in PHP?


How do I combine two different datas from Facebook and Twitter. And sort them by created_time in PHP??

Supposedly I already got the two datas from their respective API calls. But I can't seem to figure out how to combine them and sort them properly.

Example :

FB[1] TW[1]
FB[2] TW[2]
FB[3] TW[3]

If FB[1]'s created_time is much earlier than of TW[1], then FB[1] is ahead of TW[1]. If FB[2]'s created_time is later than of TW[2], then FB[2] is behind of TW[1]. If FB[3]'s created_time is the same as of TW[3], then the post would be from FB first then TW.

I got this pseudocode stuck in my head, I just can't figure out how to sort it.

I need this for my project. Please Help.

EDIT: I am using CodeIgniter.. :)


Solution

  • I don't know which kind of data do you retrieved from fb and tw, but it should be something like this if both are numeric indexed, and the next dimension has the created_time field:

    function cbSort($a, $b) {
       return $a['created_time]>$b['created_time'];
    }
    
    $res=array_merge($fb, $tw);
    usort($res, 'cbSort');    
    var_dump($res);
    

    Anyway in what you are trying to acomplish the best option would be to normalize the posts to a generic custom class.