将php数组数据导出为CSV或Excel
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了将php数组数据导出为CSV或Excel相关的知识,希望对你有一定的参考价值。
变量$ list存储一个如下所示的数组。我需要将数组传递给CSV或XLS并发送标头以下载文件。
print_r($ list)显示以下内容:
Array
(
[0] => Array
(
[warehouse] => Array
(
[warehouseName] => Warehouse Europe
[warehouseType] => en detail
)
[products] => Array
(
[0] => Array
(
[productName] => APPAREL SHIRTS
[productCode] => 54059761696
[measuringUnit] => buc
[quantity] => 1
)
[1] => Array
(
[productName] => T-SHIRTS - SADAL
[productCode] => 54059764755
[measuringUnit] => buc
[quantity] => 0
)
........... more data ............
[5315] => Array
(
[productName] => Ski - COLBECK
[productCode] => 54080519051
[measuringUnit] => buc
[quantity] => 3
)
)
)
[1] => Array
(
[warehouse] => Array
(
[warehouseName] => Warehouse US
[warehouseType] => en detail
)
[products] => Array
(
[0] => Array
(
[productName] => T-SHIRTS - SHEW
[productCode] => 40059763901
[measuringUnit] => buc
[quantity] => 5
)
[1] => Array
(
[productName] => SHOESSHOES - OPTIMA
[productCode] => 45063556796
[measuringUnit] => buc
[quantity] => 2
)
........... more data ............
[3178] => Array
(
[productName] => Ski - CASTINE
[productCode] => 40080490213
[measuringUnit] => buc
[quantity] => 1
)
)
)
)
CSV在excel中看起来像这样:example我试了好几次但我无法处理它。我认为foreach函数和fputcsv应该可以解决问题。
/////后期编辑/////
这解决了,谢谢!
foreach($list as $item){
foreach($item['products'] as $product){
$wName = $item['warehouse']['warehouseName'];
$wType = $item['warehouse']['warehouseType'];
$pr =implode(',',$product);
printf("%s,%s,%s".php_EOL,$wName,$wType,$pr);
}
}
答案
我使用了更多易于理解的变量。你可以减少它们,你可以用sprintf或file_put_content替换printf和echo函数以及你想要的一切
foreach($list as $item)
{
foreach($item['products'] as $product){
$wName = $item['warehouse']['warehouseName'];
$wType = $item['warehouse']['warehouseType'];
$pr =implode(',',$product);
printf("%s,%s,%s".PHP_EOL,$wName,$wType,$pr);
}
echo "...,...,...,...,...,...";
}
以上是关于将php数组数据导出为CSV或Excel的主要内容,如果未能解决你的问题,请参考以下文章
在 laravel 中导出 excel 或 csv 中的多维数组
php使用ajax导出CSV或者EXCEl(thinkphp)方法