循环通过多维数组来查找某些值

时间:2011-12-20 02:48:17

标签: php multidimensional-array

这里的目标是遍历下面的多维数组,找到居住在某个城市的用户。我只粘贴了阵列的一小部分,这样你就能感受到结构。它来自Facebook Graph API。下面的函数会回显此错误消息:警告:在第143行的C:\ xampp \ htdocs \ pathweavr \ friendtest.php中为foreach()提供的参数无效

第143行:

    foreach ($location['city'] as $city) {      

这是代码:

    $friends = $fqlResult;
    $friends_BA = array();
    foreach ($friends as $friend) {
    $isBA = false;
       if (is_array($friend['current_location'])) {
          foreach ($friend['current_location'] as $location) {
             if (isset($location)) {
                foreach ($location['city'] as $city) {
                   $lowerName = strtolower($city);
                   if (strpos($lowerName, 'orlando') !== false || strpos($lowerName, 'gainesville') !== false) {
                   $friends_BA[] = $friend['name'];
                   continue 3; // skip to the next friend
                   }
                 }
               }
            }
         }
      }

    d($friends_BA);

数组如下所示:

 Array
(
[0] => Array
(
    [name] => PERSONS NAME
    [current_location] => Array
        (
            [city] => New York
            [state] => New York
            [country] => United States
            [zip] => 
            [id] => 108424279189115
            [name] => New York, New York
        )

)

 [1] => Array
(
    [name] => PERSONS NAME
    [current_location] => 
)

 [2] => Array
(
    [name] => PERSONS NAME
    [current_location] => 
)

 [3] => Array
(
    [name] => PERSONS NAME
    [current_location] => 
)

 [4] => Array
(
    [name] => PERSONS NAME
    [current_location] => Array
        (
            [city] => San Jose
            [state] => California
            [country] => United States
            [zip] => 
            [id] => 111948542155151
            [name] => San Jose, California
        )

)

 [5] => Array
(
    [name] => PERSONS NAME
    [current_location] => Array
        (
            [city] => Boston
            [state] => Massachusetts
            [country] => United States
            [zip] => 
            [id] => 106003956105810
            [name] => Boston, Massachusetts
        )

)

一直在玩它一个小时,但似乎无法使它工作。我在第二个foreach声明中得到了无效的论据。

3 个答案:

答案 0 :(得分:1)

这是$location['city']不是数组。这是一个字符串变量。 foreach仅循环遍历数组。

答案 1 :(得分:1)

你不需要2个foreach的

$friends = $fqlResult;
$friends_BA = array();
foreach ($friends as $friend) {
  $isBA = false;
  if (is_array($friend['current_location'])) {
    $lowerName = strtolower($friend['current_location']['city']);
    if (strpos($lowerName, 'orlando') !== false || strpos($lowerName, 'gainesville') !== false) {
      $friends_BA[] = $friend['name'];
    }
  }
}

d($friends_BA);

答案 2 :(得分:0)

$location['city']永远不是数据结构中的数组。你试图迭代一个标量。