how to use in foreach for array_keys
Question
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)
.
OTHER TIPS
If i understand your question correctly (and I am not sure that I do) you might want something like
$by_id = array();
foreach ($friends['data'] as $item) {
$by_id[ $item['id'] ] = $item['name'];
}
Which will give you and array that looks like this:
print_r ($by_id);
Array
(
[554089741] => Tal Rozner
[559274789] => Daniel Kagan
[100001553261234] => ron cohen
)
Which might be easier for you to work with...
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow