3

I have decoded the JSON response fron facebook using $my_friends = json_decode(file_get_contents($frens));and print_r($my_friends); gives the following response :

    stdClass Object
(
    [data] => Array
        (
            [0] => stdClass Object
                (
                    [name] => Mrinal Kumar Rai Baruah
                    [id] => 546111977
                )

            [1] => stdClass Object
                (
                    [name] => Roshan Khangembam
                    [id] => 553139665
                )

            [2] => stdClass Object
                (
                    [name] => Tarunesh Kumar Saurav
                    [id] => 620690126
                )
.........................
        )

)

I am new to JSON and m very confused . How can I iterate the above response to get the name ?

Suraj Hazarika
  • 587
  • 3
  • 8
  • 22
  • Investigate the second parameter to [`json_decode()`](http://php.net/json_decode) to receive a plain array. Then read up on [`foreach`](http://php.net/foreach) and probably basic [`array`](http://php.net/array) handling (as that's what you implicate with "json"). – mario Sep 01 '11 at 17:58

1 Answers1

6
foreach($my_friends['data'] as $key => $val) {
   echo "Friend #{$key} = {$val['name']}\n";
}
Marc B
  • 340,537
  • 37
  • 382
  • 468
  • Thanks for your quick reply Marc....but it says "Cannot use object of type stdClass as array" ! – Suraj Hazarika Sep 01 '11 at 17:57
  • 2
    If you're using json_decode, do `json_decode($json, true)`, which'll force it to return an array instead of an object. Use `{$val->name}` instead of `{$val['name']}` otherwise. – Marc B Sep 01 '11 at 17:58
  • Thanks Marc....its working perfectly now . What does stdClass Object means here ? – Suraj Hazarika Sep 01 '11 at 18:19
  • 1
    It's PHP's "generic Object" class: http://stackoverflow.com/questions/931407/what-is-stdclass-in-php – Marc B Sep 01 '11 at 18:33