2015-09-21 257 views
-1

我有以下處理推文數據的小代碼。我期望我的循環迭代10次。但是,什麼情況是,它迭代一次,然後退出,沒有涉及到MySQL或其他任何錯誤的跡象。爲什麼循環只執行一次?

$query = "select data from tweets where `screen_name` = 'username' limit 10"; 
$tweetsq = mysqli_query($mysqli, $query) or die(mysqli_error($mysqli)); 
$tweets = mysqli_fetch_assoc($tweetsq); 
$tweets_count = mysqli_num_rows($tweetsq); 
echo $tweets_count . '<br />'; //See output 

$count = 0; 
foreach ($tweets as $raw_tweet) { 
    $tweet = json_decode($raw_tweet); 
    $tweet_id = $tweet->id_str; 
    $is_reply = (isset($tweet->in_reply_to_screen_name) && strlen($tweet->in_reply_to_screen_name) > 0) ? 1 : 0; 
    $is_retweet = (isset($tweet->retweeted_status) && $tweet->retweeted_status != '') ? 1 : 0; 
    $entity_holder = array(); 
    $has_hashtag = $has_url = $has_mention = $has_media = 0; 
    foreach ($tweet->entities as $type => $entity) { 
     if (is_array($entity) && count($entity) < 1) { 
      //continue; 
     } else { 
      $entity = array_pop($entity); 
      switch ($type) { 
       case 'hashtags' : $has_hashtag = 1; break; 
       case 'urls' : $has_url = 1; break; 
       case 'user_mentions' : $has_mention = 1; break; 
       case 'media' : $has_media = 1; break; 
       default : 

      } 
     } 
    } 
    echo 'Updating recorde... <br />'; 
    $query = "UPDATE tweets SET is_reply='" . $is_reply . "' , is_retweet='" . $is_retweet . "', has_hashtag='" . $has_hashtag . "', has_url='" . $has_url . "', has_mention='" . $has_mention . "', has_media='" . $has_media . "' WHERE tweet_id='" . $tweet_id . "'"; 
    $result = mysqli_query($mysqli, $query) or die(mysqli_error($mysqli)); 
    var_dump($result); //See output 
    $count++; 
    echo '<br />'; 
} 
echo $count; 

輸出

10 //This is the value of $tweets_count 
Updating recorde... 
bool(true) //The result of the UPDATE query 
1 //The value of $count at the end of script. It SHOULD be 10 
+0

你通過'$ tweets'循環,而不是'$ tweetsq '。當您迴應'$ tweetsq'的計數時,您正在通過'$ tweets'循環。你有沒有試過迴應'$ tweets'的計數? – vanamerongen

+0

@vanamerongen好的。只是'echo sizeof($ tweets)'並且它返回了'2'!這很奇怪,因爲我有超過30條匹配查詢的記錄。 – iTurki

+0

難道是因爲您使用的是http://www.w3schools.com/php/func_mysqli_fetch_assoc.asp?改爲嘗試http://www.w3schools.com/php/func_mysqli_fetch_all.asp。 – vanamerongen

回答

1

mysqli_fetch_assoc單行作爲關聯數組,其中鍵是列名,值是該列的值。使用它的正確方法是遍歷結果集,直到獲取回報NULL,表明有沒有更多的行獲取:

while ($row = mysqli_fetch_assoc($tweetsq)) { 
    $raw_tweet = $row["data"]; 
    $tweet = json_decode($raw_tweet); 
    $tweet_id = $tweet->id_str; 
    # etc... 
+0

這是做到這一點的正確方法:)沒有計算等問題。只需獲取並對每個結果執行一些操作即可。雖然我認爲在這種情況下,他正在尋找fetch_all – vanamerongen

+1

完美的作品!感謝你們兩位。 – iTurki