在PHP中迭代数组

时间:2012-02-10 01:38:23

标签: php

我对PHP很新,但我必须快速制作。

 $fql = "SELECT uid, name, pic_square, sex 
         FROM user 
         WHERE uid IN (SELECT uid2 FROM friend WHERE uid1 = me())";

      $response = $facebook->api(array(
           'method' => 'fql.query',
           'query' =>$fql,
         ));

    $allUsers = $mapper->getAll();

所以我得到了$ response,例如,$response[0]["name"]返回第一个用户的名字,$response[0]["id"]返回第一个用户的id。

然后我得到了$ allUsers数组,其中包含了所有用户id。对于$allUsers[0]->id,返回第一个用户的ID。

好的,现在结果我想过滤$ response数组,并且只包含其id在$ allUsers数组中的用户。它可能是新数组,例如$ filteredResponse。

非常感谢你的帮助,这真的只是我不知道语法的问题

我是这样写的:

$filteredResult = array();

    foreach ($response as &$userfb) {
        foreach($allUsers as &$userdb){
            if($userfb["id"] == $userdb->id){
                array_push($filteredResult, $userfb);
                break 1;
            }
        }
    }

这是对的吗?

1 个答案:

答案 0 :(得分:2)

使用这种模式你会经常使用它。

// First for each loop takes each element of the 1st array and makes it a variable.
foreach ($response as resposeData)
{
   // the second foreach loop goes through the 2nd level array.
   // since it is a hash array we ask to give us the hash key and it's value.
   // This allows for us to use if conditionals to decide what to do with the data.
   foreach ($responseData as $key => $val)
   {
   }
}