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条)

报告相同问题?

悬赏问题

  • ¥15 linux驱动,linux应用,多线程
  • ¥20 我要一个分身加定位两个功能的安卓app
  • ¥15 基于FOC驱动器,如何实现卡丁车下坡无阻力的遛坡的效果
  • ¥15 IAR程序莫名变量多重定义
  • ¥15 (标签-UDP|关键词-client)
  • ¥15 关于库卡officelite无法与虚拟机通讯的问题
  • ¥15 目标检测项目无法读取视频
  • ¥15 GEO datasets中基因芯片数据仅仅提供了normalized signal如何进行差异分析
  • ¥100 求采集电商背景音乐的方法
  • ¥15 数学建模竞赛求指导帮助