facebookfacebook-graph-apialphabeticalfacebook-friends

Sort Facebook friends alphabetically PHP SDK v5


I have a question about echoing the data that Facebook returns from the Graph API. I use the following code to get the the facebook friends using my app and their profile picture (and the ID because later I need to match them to my database:

$response = $fb->get('/me/friends?fields=picture{url},id,name');

// Get the base class GraphNode from the response
$graphEdge = $response->getGraphEdge();


foreach($graphEdge as $item):

How can I order the response so that my friends are ordered alphabetically. I have tried a lot but can't seem to figure it out.

I for example found the following code:

usort($graphEdge, function($a, $b) {
    return $a['name'] - $b['name'];
});

But i think I might be calling the array wrong ($graphEdge)

array example from facebook is as following:

 [0]=>
      array(3) {
        ["id"]=>
        string(17) "12345678901112131"
        ["name"]=>
        string(13) "John DOe"
        ["picture"]=>
        array(1) {
          ["data"]=>
          array(1) {
            ["url"]=>
            string(222) "https://fbcdn-profile-a.akamaihd.net/hprofile-ak-xfp1/v/t1.0-1/p50x50/etc."
          }
        }
      }

Solution

  • I found the solution.

    Needed to get the response from the facebook API as an array. Rookie mistake I guess.

    Hope it helps somebody:

    $graphEdge = $response->getGraphEdge()->asArray();
    
    
    function sortByOrder($a, $b) {
        return $a['name'] - $b['name']; }
    
    usort($graphEdge, 'sortByOrder');