我有以下多维数组,其中父键是长哈希值,每个哈希值都包含许多key =>值对,这些值导致以下PHP数据结构:
数组([riCQTaeQmczjR7ynRB30wzCghOhN3T82h9qXYl8M] =>数组([时间戳] => 2018-03-28 21:47:53 [你叫什么名字?] => Alberto [你想什么时候预订] =>明天)[wD5bb9lNTxmb3EftdenrO3UMJThMQ6mDhpKQFvjC] =>数组([时间戳] => 2018-03-28 21:48:10 [你叫什么名字?] => AAA [你想什么时候预订] =>下周) [02tgD3iOH2pIyrku1m9uukwwFeISHis7C9TlMaPR] =>数组([时间戳] => 2018-03-28 23:30:16 [你叫什么名字?] => Osvaldo [你想什么时候预订] =>下周)[aPjjcwhr2HeuFOaw3Jc0ijsf6C5VtAxOquSduIOP ] =>数组([时间戳] => 2018-03-28 23:31:16 [你的名字是什么?] => Jhonny [你想什么时候预订] =>明天))
上面的数据结构也可以直观地表示为:
请注意,每个父元素(即长哈希)始终包含与所有其他元素相同的键(在此示例中,每个父元素包含1个时间戳和2个问答对)。
我的目标是将此多维数组转换为以下类似于表的格式,可以在csv文件中轻松导出:
"Timestamp","What's your name?","When do you want to book?"
"2018-03-28 21:47:53","Lorna","tomorrow"
"2018-03-28 21:48:10","Jake","next week"
"2018-03-28 23:30:16","Sarah","next week"
"2018-03-28 23:31:16","Johnny","tomorrow"
数组键成为“标题”,而每行代表一个答案。
我认为一种方法是使用PHP函数array_map()
,但我无法达到预期的结果。关于如何做到这一点的任何想法/提示?
答案 0 :(得分:1)
<?php
$data = [
[
'Timestamp' => '2018-03-01',
'What\'s your name?' => 'Johnny',
'When do you want to book?' => 'tomorrow'
],
[
'Timestamp' => '2018-03-01',
'What\'s your name?' => 'Johnny',
'When do you want to book?' => 'tomorrow'
],
[
'Timestamp' => '2018-03-01',
'What\'s your name?' => 'Johnny',
'When do you want to book?' => 'tomorrow'
],
];
// get the headers
$headers = array_keys(array_values($data)[0]);
// open the file
$resource = fopen('output.csv', 'w');
// put the headers
fputcsv($resource, $headers);
// put the data
foreach ($data as $d) {
fputcsv($resource, $d);
}
// close the file
fclose($resource);