循环遍历数组以获取值

时间:2012-06-25 18:14:57

标签: php arrays

  

可能重复:
  php loop through associative arrays

我有一个变量,它打印一个名为$ friends的数组,它的输出是这样的:

{
  "data": [
    {
      "name": "Penelope-ns-test",
      "category": "Community",
      "id": "187099821418102",
      "created_time": "2012-06-14T15:00:59+0000"
    },
    {
      "name": "Fabric",
      "category": "Computers/technology",
      "id": "194407767268061",
      "created_time": "2012-06-07T07:24:03+0000"
    },

等...

我需要做一个循环才能得到这样的东西:如果朋友[id] == 1203438484 {

}

ELSE ...

foreach($friends['data'] as $data){
                $fbid = $data['id'];
                $fbfriendlikes[$fbid]=$facebook->api('/'.$fbid.'/likes'); 
                $fbname = $data['name'];
                $path = $protocol . '://graph.facebook.com/' . $fbid . '/picture?type=' . $size;
                $image = theme('image', array('path' => $path, 'alt' => $fbname));
                $return .= '<div class="fimage">'.$image.'</div>';
                $link = '<a href="'.$protocol . '://www.facebook.com/profile.php?id='.$fbid.'" target="_blank">'.$fbname.'</a>';
                foreach ($fbfriendlikes["data"] as $fbfriendlikes) {
    if ($fbfriendlikes["id"] == 184759054887922) {

                $return .= '<div class="flink">'.$link.'</div>';
                break;
                }
                }
            }

你能帮我解决一下代码吗? 谢谢!

2 个答案:

答案 0 :(得分:3)

foreach ($friends["data"] as $friend) {
    if ($friend["id"] == 12345) {
        // Do something with $friend

        break;
    }
}

答案 1 :(得分:2)

foreach($array['data'] as $friend)
{
    if ($friend['id'] == 1203438484)
    {
        //do something
    }

}
相关问题