如何在while循环中使用嵌套数组?

时间:2018-02-09 15:34:09

标签: php arrays loops

我想将数据放入数组中,然后放入excel文件但不起作用。

    $sql="SELECT `Jobc_id`, `Customer_name`, `Veh_reg_no`, `MSI_cat`, `Mileage` FROM `jobcard`";
$result = $conn->query($sql);

while($row = $result->fetch_assoc()){

    array( $row["job_id"],$row["Customer_name"],$row["Veh_reg_no"],$row["MSI_cat"],$row["Mileage"]);
}
foreach($rows as $row)
    $writer->writeSheetRow('Sheet1', $row);

然而,代码下面工作..

$rows = array(
    array('2003','1','-50.5','2010-01-01 23:00:00','2012-12-31 23:00:00'),
    array('2003','B1', '23.5','2010-01-01 00:00:00','2012-12-31 00:00:00'),
); 
 foreach($rows as $row)
        $writer->writeSheetRow('Sheet1', $row);

如何使第一个代码工作:( 请帮忙

1 个答案:

答案 0 :(得分:2)

您没有将数组分配给变量,因此在while循环后无法访问获取的数据。这应该解决它:

$rows = [];
while($row = $result->fetch_assoc()){
    $rows[] = [$row["job_id"],$row["Customer_name"],$row["Veh_reg_no"],$row["MSI_cat"],$row["Mileage"]];
}
// now you can use $rows