我需要在应用程序中将db内容导出为csv文件。但是内容不是从第一行开始。它从第40行开始。在那方面,我需要做些什么?

header('Content-Encoding: UTF-8');
header("Cache-Control: cache, must-revalidate");
header("Pragma: public");
header('Content-Type: text/csv, charset=UTF-8; encoding=UTF-8');
$filename = date('Y_m_d_s');
header("Content-Disposition: attachment; filename=\"".$filename.".csv\"");

if($dbResult) {
    $cnthead=0; $cntr =count($dbResult[0])-1;
    foreach($dbResult[0] as $key => $Val){
        echo $key;
        if($cnthead < $cntr) {
            echo ",";
            $cnthead++;
        }
    }
    echo "\n";
    foreach($dbResult as $dbRes){
        $cntcontnt=0;
        foreach($dbRes as $dbVal){
            echo $dbVal;
            if($cntcontnt < $cntr) {
                echo ",";
                $cntcontnt++;
            }
        }
        echo "\n";
    }
}


$ dbResult数组如下所示,

Array
(
    [0] => Array
        (
            [Appraisee Name] => aaa R
            [Team] => Software
            [Appraisee Emp No] => -
            [Appraiser Name] => vvv A
            [Appraiser Emp No] => -
            [Reviewer Name] => sss S
            [Reviewer Emp No] => -
            [Current Appraisal Status] => start
        )

    [1] => Array
        (
            [Appraisee Name] => gan R
            [Team] => Software
            [Appraisee Emp No] => -
            [Appraiser Name] => fcv R
            [Appraiser Emp No] => -
            [Reviewer Name] => sss S
            [Reviewer Emp No] => -
            [Current Appraisal Status] => start
        )
)

最佳答案

我想问题从这里开始

$cntr =count($dbResult[0])-1; //so $cntr = 7;

foreach($dbResult[0] as $key => $Val){
    echo $key;
    if($cnthead < $cntr) {//this condition only true for first 7 loops after it will fails
        echo ",";
        $cnthead++;
    }
}


例如,$ dbResult有7条以上的记录,它将不会进入第一个forloop if语句。如果要循环$ dbResult所有记录,则按如下所示更改代码。

我想你需要改变

$cntr =count($dbResult[0])-1;


进入

$cntr =count($dbResult)-1;


尝试在您的代码中进行此更改

10-06 16:11