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 目详情-五一模拟赛详情页
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line