循环通过Facebook JSON对象

时间:2013-11-16 03:02:28

标签: php json

我目前正在获得我想要的输出,虽然看起来我能使这个工作的唯一方法是使用这些令人讨厌的嵌套foreach循环。我知道必须有一个更好的方法来循环这个JSON对象。     

$json = 'https://graph.facebook.com/218894654822767_609825405729688?fields=id,likes&key=value&access_token=245675758812857%7Ca2b43c96b8f2db07561ac8f6054b2632';

$fbObject = file_get_contents($json);

$array = json_decode($fbObject, true);

$count = 0;
if(is_array($array))
{
  foreach ($array as $key => $object) {
    if(is_array($object))
    {
      foreach ($object as $likes){
        if(is_array($likes))
        {
          foreach ( $likes as $data ){
            if(is_array($data))
            {
             foreach ( $data as $id ){
              if (is_numeric($id))
                {
                  echo "$id".'<br />';
                } 
              }
            }
          }
        }
      }
    }
  } 

}

&GT;

1 个答案:

答案 0 :(得分:0)

简化:

$json_url = 'https://graph.facebook.com/218894654822767_609825405729688?fields=id,likes&key=value&access_token=245675758812857%7Ca2b43c96b8f2db07561ac8f6054b2632';
$json = json_decode(file_get_contents($json_url));
$user_ids = array();

foreach ($json->likes->data as $user) {
    $user_ids[] = $user->id;
}

print implode('<br />', $user_ids);

更简化:

$json_url = 'https://graph.facebook.com/218894654822767_609825405729688?fields=id,likes&key=value&access_token=245675758812857%7Ca2b43c96b8f2db07561ac8f6054b2632';
$json = json_decode(file_get_contents($json_url));

print implode('<br />', array_map(function ($user) {
        return $user->id;
    }, (array) $json->likes->data));

这就是全部! :)