2017-05-09 76 views
-2

這裏我的代碼在class.php:的foreach的foreach錯誤內

public function select(){ 
     $stmt = $this->conn->prepare("SELECT country FROM `country`") or die($this->conn->error); 
     if($stmt->execute()){ 
      $result = $stmt->get_result(); 
      return $result; 
     } 
    } 


public function read(){ 
     $stmt = $this->conn->prepare("SELECT segment FROM `segments`") or die($this->conn->error); 
     if($stmt->execute()){ 
      $result = $stmt->get_result(); 
      return $result; 
     } 
    } 

而現在的index.php我這樣做:

      <th class="text-center">country</th> 

          <th class="text-center">segments</th> 
      </thead> 
      <tbody> 
      <?php 

       require 'class.php'; 

       $conn = new db_class(); 
       $read = $conn->select(); 
            $test = $conn->read(); 

       while($fetch = $read->fetch_array(MYSQLI_ASSOC)&& $fetch1 = $test->fetch_array(MYSQLI_ASSOC)){ 
             foreach ($fetch1 as $field => $values) { 


             foreach($fetch as $field=>$value){ 
    echo '<tr><td>' . $value . '</td>' 
      . '<td>'. $values .'</td>'; 
} 

             } 
}  


      ?> 




      </tbody> 
     </table> 

我只是想獲取數據從2個表格,並把它們放在一個HTML表格

我得到這個錯誤6次:

Warning: Invalid argument supplied for foreach() in C:\Program Files (x86)\EasyPHP-DevServer-14.1VC11\data\localweb\segments\countrySegment.php on line 59

我只是試圖從兩個表中獲取數據,並把它們放在一個HTML表格 ,如果任何人知道怎麼樣,我想對每一個國家的下拉菜單,段值內 什麼想法?感謝ü提前

+0

你能在循環中打印$ fetch' && $ fetch1嗎? –

+0

它出現了這個錯誤:數組到字符串的轉換@AgamBanga –

+0

做'print_r($ fetch)'&&'print_r($ fetch1)'而不是'echo' –

回答

1

這是因爲數組指針問題

foreach ($fetch1 as $field => $values) { 
    foreach($fetch as $field=>$value){ 
     echo '<tr><td>' . $value . '</td>' 
      . '<td>'. $values .'</td>'; 
    } 
} 

第一次第二的foreach一切打印下一次它沒有價值指向超越的價值..

,所以你需要重新設置使用復位

foreach ($fetch1 as $field => $values) { 
    reset($fetch) 
    foreach($fetch as $field=>$value){ 
     echo '<tr><td>' . $value . '</td>' 
      . '<td>'. $values .'</td>'; 
    } 
} 

或可以保存臨時變量陣列

foreach ($fetch1 as $field => $values) { 
    $fetchtmp = $fetch; 
    foreach($fetchtmp as $field=>$value){ 
     echo '<tr><td>' . $value . '</td>' 
      . '<td>'. $values .'</td>'; 
    } 
} 
+0

謝謝你,但它不工作仍然有相同的錯誤 –

+0

哪個選項你試過 –

+0

這兩個選項@ v-sugumar –