给定一个这样的数组。
[
[
'first_name' => 'Bill',
'last_name' => 'Johnson',
'telephone' => '123-456-7890'
],
[
'first_name' => 'Kurtis',
'last_name' => 'Wild',
'telephone' => '321-654-0987'
],
[
'first_name' => 'Jane',
'last_name' => 'Doe',
'email' => '[email protected]'
]
]
我需要写出一个CSV格式的东西,就像这样
+------------+-----------+--------------+-------------------+
| first_name | last_name | telephone | email |
+------------+-----------+--------------+-------------------+
| Bill | Johnson | 123-456-7890 | |
| Kurtis | Wild | 321-654-0987 | |
| Jane | Doe | | [email protected] |
+------------+-----------+--------------+-------------------+
困难的是 telephone
和 email
列是动态的。它们存在于某些行,但不存在于其他行,而且可以有任何数量的这些字段只存在于行的子集上。所有的行都有 做 共享某个字段的行需要该字段在同一列定位。行中的 勿 这个字段的单元格应该是空的。
我想我要找的是一种通用的方法,将一个关联数组如上图所示,并转储出一个代表CSV的字符串,使用数组键作为标题,同时注意它们不会跨行匹配。
我已经尝试过将这样一个数组传递到 fgetcsv()
,还尝试了 league/csv
包,但这两个包都不支持。有谁知道有什么库可以做到这一点,或者甚至只是一个函数,可以接受这种类型的数组并吐出一个正确的CSV?
一堆 foreach
如果你想保持它的动态性,循环也可以。
# Create a key storage array
$cols = [];
foreach($arr as $row) {
foreach($row as $k => $v) {
if(!in_array($k, $cols))
$cols[$k] = '';
}
}
# Loop the main array again and merge the storage array
foreach($arr as $k => $row) {
$arr[$k] = array_merge($cols, $row);
}
给你:
Array
(
[0] => Array
(
[first_name] => Bill
[last_name] => Johnson
[telephone] => 123-456-7890
[email] =>
)
[1] => Array
(
[first_name] => Kurtis
[last_name] => Wild
[telephone] => 321-654-0987
[email] =>
)
[2] => Array
(
[first_name] => Jane
[last_name] => Doe
[telephone] =>
[email] => [email protected]
)
)
如果你想手动创建参考数组, 你可以很容易地将一个空白数组与填充数组合并,得到一个混合数组。
$cols = [
'first_name' => '',
'last_name' => '',
'email' => '',
'telephone' => ''
];
foreach($arr as $k => $row) {
$arr[$k] = array_merge($cols, $row);
}
然后得到一个混合数组:
Array
(
[0] => Array
(
[first_name] => Bill
[last_name] => Johnson
[email] =>
[telephone] => 123-456-7890
)
[1] => Array
(
[first_name] => Kurtis
[last_name] => Wild
[email] =>
[telephone] => 321-654-0987
)
[2] => Array
(
[first_name] => Jane
[last_name] => Doe
[email] => [email protected]
[telephone] =>
)
)
EDIT:
我不确定你是否需要一个数组到CSV的函数,但这里只是一个快速的函数。
function downloadCSV($rows)
{
ob_start();
$fp = fopen('php://output', 'w');
foreach ($rows as $fields) {
fputcsv($fp, $fields);
}
fclose($fp);
$str = ob_get_contents();
ob_end_clean();
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.date('YmdHis').'file.csv"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: '.strlen($str));
echo $str;
exit;
}
所以当你从上述方法中得到数组后 在任何其他浏览器输出之前运行这个函数
# $arr being your array of course
downloadCSV($arr);