簡體   English   中英

遍歷數組的問題

[英]Issues looping through an array

因此,我正在使用數據庫來存儲飛船數據。

當我將數據加載到數據庫中時,我正在檢查船是否已經存在。 有時,不止一艘船具有相同的名稱。 這段代碼嘗試遍歷數組,拔出所有具有相同名稱的飛船,然后依次詢問是否正確(如果不是),則又是另一個具有相同名稱的船只。

 $sql = "SELECT Ship_Primary_Key, ship_original_rate, Ship_Launch_Year from Ships WHERE Ship_Name = '" . $shipname . "'";
 $result = $conn->query ($sql);
 if ($result-> num_rows > 0) //Does the ship name already exist in the DB? {
     $ships_in_db = mysqli_fetch_all ($result,MYSQLI_ASSOC); 
     foreach ($ships_in_db as $row) {
         echo "new record is " . $shipname . " as a " . $shiprate . ". Records already include " . $shipname . ", launched " . $row["Ship_Launch_Year"] . " as a " .  $row ['ship_original_ra
         $yesno = trim(fread(STDIN,5));
         if ($yesno == "y" || $yesno == "yes") {
             //ship already exists in the DB. Get the Key
             echo $shipname . " is not new to the database and the key is " . $row["Ship_Primary_Key"]  . "\n";
             $shipkey = $row["Ship_Primary_Key"];
             break 1;
          }
      }

      //if you get through the loop of ships without assigning a primary key, ship is new
      if (empty($shipkey)) {
          $shipkey = write_ship_to_DB($shipname,$shiprate,$launchyear,$launchname,$conn);
      }
  }

所以問題是,我知道我在第一組數據中至少有三艘同名船(不同)。 問題是,它只詢問第一個。 當我輸入“ n”時,它一直在繼續,並且從未詢問過具有相同名稱的第二艘船。

我認為這與Foreach循環和break語句有關。 我對此表示感謝

我已經解決了問題。

由於存在循環,我沒有重置“ Ship_Id”變量,這意味着同名船只第二次或第n次出現時,沒有創建新船。

現在我已經解決了。 因此,問題根本不在於此代碼,而是其他代碼。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM