douzhao7445 2014-07-30 11:08
浏览 26
已采纳

在CakePHP中以CSV格式导出mysql数据

In CakePHP, with the following code i am trying to Export users email in CSV. I am getting Errors.

Code Refrence site

Error:

Notice (8): Undefined offset: 0 [APP\View\Frontusers\admin_exportemails.ctp, line 12]

Warning (2): fputcsv() expects parameter 2 to be array, null given [APP\View\Helper\CsvHelper.php, line 36]

Notice (8): Undefined offset: 1 [APP\View\Frontusers\admin_exportemails.ctp, line 12]

Warning (2): fputcsv() expects parameter 2 to be array, null given [APP\View\Helper\CsvHelper.php, line 36]

admin_exportemails.ctp

$line= $useremails[0]['Frontuser'];
$this->CSV->addRow(array_keys($line));

foreach ($useremails as $key => $useremail)
{
      $line =$useremail[$key]['Frontuser'];
       $this->CSV->addRow($line);
}
$filename='useremails';
echo  $this->CSV->render($filename);
  • 写回答

5条回答 默认 最新

  • dro60731 2014-07-30 11:31
    关注

    You're messing up your foreach. You split it up in the $key and the $useremail sub-array, which is OK. But then you iterate over it and try to access $useremail[$key]['Frontuser'] again, which is nonexistent at that point.

    foreach ($useremails as $key => $useremail)
    

    This causes the [0] and [1] in the original $useremails array to be set as $key, but you iterate over all the items over the $useremails, so you can simply:

    $line = $useremail['Frontuser'];
    

    You don't need the $key, since that's not part of the iterated item, e.g. the first time your foreach runs, it sees this:

    [Frontuser] => Array
        (
            [name] => Rash
            [email] => rash.com
        )
    

    And on the second iteration it sees this:

    [Frontuser] => Array
        (
            [name] => John
            [email] => john@gmail.com
        )
    

    So there is no [0] or [1] index anymore.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥30 comsol仿真等离激元
  • ¥15 静电纺丝煅烧后如何得到柔性纤维
  • ¥15 (标签-react native|关键词-镜像源)
  • ¥100 照片生成3D人脸视频
  • ¥15 伪装视频时长问题修改MP4的时长问题,
  • ¥15 JETSON NANO
  • ¥15 VS开发qt时如何在paintgl函数中用pushbutton控制切换纹理
  • ¥20 关于 openpyxl 处理excel文件地问题
  • ¥15 MS中不知道高分子的构型怎么构建模型
  • ¥60 QQOP数据,什么是op数据号,怎么提取op数据!能不能大量提取(语言-c语言)