2014-02-17 218 views
0

我想創建一個包含SQL表結果的數組。但我的foreach循環似乎沒有正確的功能。Foreach PHP循環到數組

這是我的代碼: $ stmt-> bind_param(「i」,$ id); $ stmt-> execute(); ($ stmt-> fetch()){ } $ stmt-> close();

$i = 0; 
    foreach ($connected_items as &$value) { 
      print_r ($connected_items[$i]); 
      $stmt->bind_param("i", $connected_items[$i]); 
      $stmt->execute(); 
      while ($stmt->fetch()) { 
       $result[] = array(, 
         ); 
      } 
      $stmt->close(); 

      $i++; 
      } 
    unset($value); 
    ) 
) 

這似乎是運行在for循環在我的打印語句,然後MySQL的語句,使用最後connected_items_id,這是爲什麼?爲什麼它不返回該ID的關聯值?

回答

1

刪除此[]在行號6:

while ($stmt->fetch()) { 
    $connected_items = array($connected_items_id); 
} 

取而代之:

while ($stmt->fetch()) { 
    $connected_items[] = array($connected_items_id); 
} 
1

嘗試

foreach ($connected_items as $value) { 
...................... 
...................... 
$stmt = $this->db->prepare('SELECT name, serial FROM `glpi_monitors` WHERE id =?'); 
$stmt->bind_param("i", $value[0]); 
................................ 
................................ 
} 

你也可以用它代替循環,每次查詢IN關鍵字。

$sql = "SELECT name, serial FROM `glpi_monitors` WHERE id IN('".implode("','",$connected_items)."'"); 
$stmt = $this->db->prepare($sql); 

例如:

1

嘗試此,

"connected_item_id" => $connected_items[0], 

代替

"connected_item_id" => $connected_items_id,