2017-05-09 73 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 –