使用PHP将多维数组展平为csv文本 [英] flatten multidimensional array into csv text with PHP
问题描述
我知道这个问题已经问了很多遍了,但这有点曲解。
I know this has been asked quite a few times but this is a bit of a twist.
我有一个多维数组,数组的键需要成为平面csv类型字符串的列名(我不希望它作为文件,就像csv字符串一样。)。
I have a multidimensional array in which the Key of the array needs to be the column name for a flat csv-type string (I don't want it as a file, just as a csv string).
所以是这样的:
$data = array(
dates = array ('2010-01-02','2011-02-03','2011-02-04'),
type1 = array ('data1','data2','data3'),
type2 = array ('data4','data5','data6')
);
最终结果应为:
$new_data = "dates,type1,type2" . "\n"
$new_data .= "2010-01-02,data1,data4" . "\n"
$new_data .= "2011-02-03,data2,data5" . "\n"
$new_data .= "2011-02-04,data3,data6";
我希望这很清楚。谢谢您的帮助。
I hope this is clear. Thanks for any help.
推荐答案
这比您可能需要的要冗长得多,但是它使您可以n个元素的数组。 zip
基于同名的Python函数。我没有写。
This is much more verbose than you'll likely ever need, but it allows you to have an array of n elements. zip
is based off of the Python function of the same name. I did not write it.
$data = ($data);
$r = (call_user_func_array('zip', $data));
$fin = "";
$fin .= implode(',',array_keys($data)).PHP_EOL;
foreach($r as $arr)
{
$fin .= implode(',',$arr).PHP_EOL;
}
// $fin now holds all the data. Do something with it and you're finished!
function zip() {
$args = func_get_args();
$zipped = array();
$n = count($args);
for ($i=0; $i<$n; ++$i) {
reset($args[$i]);
}
while ($n) {
$tmp = array();
for ($i=0; $i<$n; ++$i) {
if (key($args[$i]) === null) {
break 2;
}
$tmp[] = current($args[$i]);
next($args[$i]);
}
$zipped[] = $tmp;
}
return $zipped;
}
(请查看评论中的对话内容。这确实很相关。)
(check out the conversation in the comments. It's really relevant.)
这篇关于使用PHP将多维数组展平为csv文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!