2011-12-20 73 views
0

此處的目標是循環遍歷下面的多維數組,並查找位於某個城市的用戶。我只粘貼了陣列的一小部分,以便您可以感覺到結構。它來自Facebook Graph API。下面這個功能回到拍攝此錯誤信息:警告:(c)中提供的foreach參數無效:\ XAMPP \ htdocs中\ pathweavr \ friendtest.php上線143通過多維數組循環查找特定值

行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 
     ) 

) 

被玩弄機智h它一個小時,但似乎無法使其工作。我在第二個foreach聲明中得到了無效的論點。

回答

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); 
+0

非常感謝。 – buttonitup 2011-12-20 03:18:33

0

$location['city']絕不是數據結構中的數組。你正試圖遍歷一個標量。

+0

沒有注意到這一點。那麼我將如何調整?我處理的所有其他變量都是數組。 – buttonitup 2011-12-20 03:05:34

1

這是$location['city']不是數組。這是一個字符串變量。 foreach只能通過數組循環。