将关联数组与mysqli_fetch_assoc()php

时间:2018-07-20 16:50:30

标签: php arrays mysqli phpexcel associative-array

我正在使用PHP Excel从数据库中存储的数据创建一个excel文档。在html表中显示数据时,它可以完美显示,但是在excel文件中,我遇到了障碍。我的代码如下:

$excelData = array(
        0 => array('Jackson','Barbara','27','F','Florida'),
        1 => array('Kimball','Andrew','25','M','Texas'),
        2 => array('Baker','John','28','M','Arkansas'),
        3 => array('Gamble','Edward','29','M','Virginia'),
        4 => array('Anderson','Kimberly','23','F','Tennessee'),
        5 => array('Houston','Franchine','25','F','Idaho'),
        6 => array('Franklin','Howard','24','M','California'),
        7 => array('Chen','Dan','26','M','Washington'),
        8 => array('Daniel','Carolyn','27','F','North Carolina'),
        9 => array('Englert','Grant','25','M','Delaware')
    );

我需要mysql数据共同创建一个上述数组。这样我就可以在下面的代码段中使用它来显示在特定的表格单元格中。

for($i=0; $i<count($excelData); $i++){
        $ii = $i+3;
        $objPHPExcel->getActiveSheet()->setCellValue('A'.$ii, $excelData[$i][0]);
        $objPHPExcel->getActiveSheet()->setCellValue('B'.$ii, $excelData[$i][1]);
        $objPHPExcel->getActiveSheet()->setCellValue('C'.$ii, $excelData[$i][2]);
        $objPHPExcel->getActiveSheet()->setCellValue('D'.$ii, $excelData[$i][3]);
        $objPHPExcel->getActiveSheet()->setCellValue('E'.$ii, $excelData[$i][4]);
}

包括mysqli查询在内的循环的完整代码如下:

$qr = "SELECT * FROM ". DB_PROJECT_DETAILS_TBL ." WHERE project_id = '$project_id' ORDER BY id DESC";
    $mx = $db->runQuery($qr);

    // check for empty result
    while ($row = mysqli_fetch_array($mx)) {
    $excelData = array(
        0 => array($row['col1'], $row['col2'], $row['col3'], $row['col4'], $row['col5'])
    );
}

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

如果我理解正确,则需要替换此代码

while ($row = mysqli_fetch_array($mx)) {
    $excelData = array(
        0 => array($row['col1'], $row['col2'], $row['col3'], $row['col4'], $row['col5'])
    );
}

使用此代码

$excelData = array();
while ($row = mysqli_fetch_array($mx)) {
    $excelData[] = array($row['col1'], $row['col2'], $row['col3'], $row['col4'], $row['col5']);
}

我也认为您可以使用此代码段。我认为这会稍微降低复杂性

$qr = <<<SQL
    SELECT
    LIST ONLY NECESSARY COLUMNS
    FROM ". DB_PROJECT_DETAILS_TBL ." 
    WHERE project_id = '$project_id' 
    ORDER BY id DESC
SQL;
$mx = $db->runQuery($qr);
$excelData = mysqli_fetch_all($mx, MYSQLI_NUM);
$objPHPExcel->getActiveSheet()->fromArray($excelData, null,'A3');