Search code examples
phpfacebookforeacharray-key

how to use in foreach for array_keys


i need to get data from array_keys the script i use in the server side:

PHP:

$friends = json_decode(file_get_contents(
'https://graph.facebook.com/me/friends?access_token=' .
   $facebook->getAccessToken() ), true);
$friend_ids = array_keys($friends);

the data of array look as above:

{
   "data": [
      {
         "name": "Tal Rozner",
         "id": "554089741"
      },
      {
         "name": "Daniel Kagan",
         "id": "559274789"
      },
  {
         "name": "ron cohen",
         "id": "100001553261234"
      }
   ]
}

i need to get all this data to an array that i can work with it.

how can i do it ? tanks,


Solution

  • Not sure what you mean "work with it." If the JSON response from Facebook is what you posted, you should be able to do this:

    foreach ($friends['data'] as $friend) {
        echo "ID: {$friend['id']}" . PHP_EOL;
        echo "ID: {$friend['name']}" . PHP_EOL;
        echo PHP_EOL;
    }
    

    This would produce:

    ID: 554089741
    Name: Tal Rozner
    
    ID: 559274789
    Name: Daniel Kagan
    
    ID: 100001553261234
    Name: ron cohen
    

    The $friends var would already be an array due to your use of json_decode(). In this case array_keys() isn't needed, and would only produce array (0, 1, 2).