【发布时间】:2020-04-26 04:41:02
【问题描述】:
我正在尝试使用以下代码将多维数组导出为 CSV 格式,但我遇到的错误很少.. 下面是数组
"orders": [
{
"id": 1,
"first_name": “test",
"last_name": “test",
"email": “test@test.gmail.com",
“Order1": [
{
"order_id": 1,
"first_name": “test",
"last_name": “test",
“Amount": 27.77
}
],
"payment": {
"id": 1,
"trans_id": 12345,
"last_four": “1111",
"total_paid": 27.77
}
},
{
"id": 2,
"first_name": “test1",
"last_name": “test1",
"email": “test1@test.gmail.com",
“Order1": [
{
"order_id": 2,
"first_name": “test1",
"last_name": “test1",
“Amount": 28.77
}
],
"payment": {
"id": 1,
"trans_id": 12346,
"last_four": “2222",
"total_paid": 28.77
}
}
]
我期待的 csv 文件的输出
1 test test test@gmail.com 1 test test 27.77 12345 1111 27.77
2 test1 test1 test1@gmail.com 2 test1 test1 28.77 12346 2222 28.77
我想将所有数据转换为 csv 文件。问题是,由于所有子数组,我似乎无法让它工作。
header('Content-Type: text/csv;');
header('Content-Disposition: attachment; filename=order.csv');
header("Pragma: no-cache");
header("Expires: 0");
$fh = fopen('php://output', 'w');
fputcsv($fh, array_keys($orders[0]));
foreach ($orders as $order) {
$result = [];
array_walk_recursive($order, function($item) use (&$result) {
$result[] = $item;
});
fputcsv($fh, $result);
}
我在这方面遇到了错误
【问题讨论】:
-
你的输出是什么,它与你想要的有什么不同?
-
我得到空的 .csv 文件。
-
单个CSV行是一维的,不能像这样表示多维数据结构。如果
Order1数组中有多个条目会怎样?每个 CSV 行可以有不同数量的列。 -
fputcsv($fh, array_keys($orders));输出是 1 个测试 test@gmail.com 数组
标签: php arrays laravel function multidimensional-array