2012-11-20 37 views
-1

Iam試圖在Facebook中從我的電影獲取我的電影中的特定號碼後突破一個foreach循環 。Foreach循環不會在PHP中破解,使用Facebook-api

我認爲這是一個小笨蛋。 這裏是我的了:

try { 
// Proceed knowing you have a logged in user who's authenticated. 
$user_movie_info = $facebook->api('/me/movies?fields=name,genre,release_date,picture,likes'); 
    } catch (FacebookApiException $e) { 
    error_log($e); 
    $user = null; 
    } 

//print_r($user_movie_info); 

$numer_of_movies_allowed = 2; 
$movie_counter = 0; 

foreach($user_movie_info['data'] as $movie) { 

    if ($movie_counter === $number_of_movies_allowed) { 
     break; 
    } 

    echo '<img src="' .$movie['picture']['data']['url']. '">'; 
    echo $movie['name']; 
    echo $movie['release_date']; 
    echo $movie['genre']; 
    echo $movie['likes']; 
    echo "</br> </br>"; 
    $movie_counter ++; 
} 

print ($movie_counter); 

print ($numer_of_movies_allowed); 

後2部電影中,沒有打出去,但顯示它們。

如果我使用:

if ($movie_counter == $number_of_movies_allowed) 

if ((int)$movie_counter === (int)$number_of_movies_allowed) 

沒有電影顯示在所有。

回答

1
$numer_of_movies_allowed = 2; 
$movie_counter = 0; 

foreach($user_movie_info['data'] as $movie) { 

    if ($movie_counter === $number_of_movies_allowed) { 

,如果你寫的變量名在初始化時正確它可以幫助... $numer_of_movies_allowed$number_of_movies_allowed不一樣。

如果你已經將error_reporting設置爲合理的開發等級,那麼這個問題就完全沒有必要了(因爲PHP會告訴你if條件裏面的變量沒有設置) - SO DO IT現在!

1
if ($movie_counter === $number_of_movies_allowed) 

應該是:

if ($movie_counter == $number_of_movies_allowed) 
+0

==可能會帶來意想不到的結果。最好將'$ movie_counter'解析爲整數(因爲它是預期的)。 – Manhim

+0

真的嗎? '$ movie_counter'被初始化爲0,然後簡單地遞增。 '$ numer_of_movies_allowed'被設置爲一個整數並且永遠不會被修改。這裏沒有真正的理由在這裏使用'===',除非你的風格在任何地方都可以使用'==='(這當然不是一個壞主意)。 – sgroves

+0

如果我使用「==」而不是「===」沒有電影可見。所以它立即爆發我想? – user1386906

1

===要求兩個數據類型是相同的。您必須將$ movie_counter解析爲int或刪除一個等號。

嘗試

if ($movie_counter == $number_of_movies_allowed) 

if ((int) $movie_counter === (int)$number_of_movies_allowed) 
+0

如果我使用「==」或(int)則沒有電影可見。所以它立即發生思考? – user1386906

0

這裏有一個表,我發現:

// "===" means that they are identical 
// "==" means that they are equal 
// "!=" means that they aren't equal. 

     false null array() 0  "0"  0x0  "0x0" "000" "0000" 
false ===  ==  ==  ==  ==  ==  !=  !=  !=  
null  ==  ===  ==  ==  !=  ==  !=  !=  !=  
array() ==  ==  ===  !=  !=  !=  !=  !=  !=  
0  ==  ==  !=  ===  ==  ===  ==  ==  ==  
"0"  ==  !=  !=  ==  === ==  ==  ==  ==  
0x0  ==  ==  !=  ===  ==  ===  ==  ==  ==  
"0x0" !=  !=  !=  ==  ==  ==  ===  ==  ==  
"000" !=  !=  !=  ==  ==  ==  ==  ===  ==  
"0000" !=  !=  !=  ==  ==  ==  ==  ==  ===