0

我正在使用 PHPExcel 编写 XLS 文件。但我需要一种方法来根据我从数据库获得的结果自动设置单元格的数量。这就是我使用增量$n. 问题是所有的工作都在第一个foreach中,但在第二个中,前一个的值$n丢失了,它覆盖了以前的单元格。如何将增量的值保持在循环$n之外?foreach这是我到目前为止所做的:

$objPHPExcel->getActiveSheet()->SetCellValue('A7', 'Tot number unique visits per device:');
    $n=7;
    foreach ($visits_by_device as $key) {
        $n = $n++;
        $objPHPExcel->getActiveSheet()->SetCellValue('A'.$n, $key["device_type"]);
        $objPHPExcel->getActiveSheet()->SetCellValue('B'.$n, $key["tot"]);
    }
    $objPHPExcel->getActiveSheet()->SetCellValue('A'.$n, 'Tot number Unique Visits per Date:');
    foreach ($visits_by_date as $key) {
        $objPHPExcel->getActiveSheet()->SetCellValue('A'.$n, $key["date"]);
        $objPHPExcel->getActiveSheet()->SetCellValue('B'.$n, $key["tot"]);
    }
4

3 回答 3

1

很简单...只需给它一个单独的变量,例如本例中的 $k

$objPHPExcel->getActiveSheet()->SetCellValue('A7', 'Tot number unique visits per device:');
$n=7;
$k=$n
foreach ($visits_by_device as $key) {
    $n = $n++;
    $objPHPExcel->getActiveSheet()->SetCellValue('A'.$n, $key["device_type"]);
    $objPHPExcel->getActiveSheet()->SetCellValue('B'.$n, $key["tot"]);
}
$objPHPExcel->getActiveSheet()->SetCellValue('A'.$n, 'Tot number Unique Visits per Date:');
foreach ($visits_by_date as $key) {
 $k = $k++;
    $objPHPExcel->getActiveSheet()->SetCellValue('A'.$k, $key["date"]);
    $objPHPExcel->getActiveSheet()->SetCellValue('B'.$k, $key["tot"]);
}
于 2013-06-10T08:23:29.637 回答
0

只需$n++在第二个循环的开头添加 即可继续计数$n

$n = 7;
foreach ($visits_by_device as $key) {
    $n++;
    $objPHPExcel->getActiveSheet()->SetCellValue('A'.$n, $key["device_type"]);
    $objPHPExcel->getActiveSheet()->SetCellValue('B'.$n, $key["tot"]);
}

$n = 7; add this line if you want to count from 7 again. Remove it to continue counting.
$objPHPExcel->getActiveSheet()->SetCellValue('A'.$n, 'Tot number Unique Visits per Date:');
foreach ($visits_by_date as $key) {
    $n++;
    $objPHPExcel->getActiveSheet()->SetCellValue('A'.$n, $key["date"]);
    $objPHPExcel->getActiveSheet()->SetCellValue('B'.$n, $key["tot"]);
}
于 2013-06-10T08:24:35.077 回答
0

使用static关键字来保持变量的值,如下所示:

static $n=7;

这将保留以前的值,并且不会丢失该值。

于 2013-06-10T08:25:30.103 回答