在PHP中使用带键的数组进行内爆
我需要在PHP中将数组写入.csv文件 示例阵列:在PHP中使用带键的数组进行内爆,php,arrays,csv,Php,Arrays,Csv,我需要在PHP中将数组写入.csv文件 示例阵列: $array = array( "name" => "John", "surname" => "Doe", "email" => "nowhere@nowhere.com" ); 通过使用内爆(“,”,$array),我得到如下结果: 约翰,多伊,nowhere@nowhere.com 但是,我还需要将每个元素的键写入文件。 所需的输出如下: 姓名:约翰,姓氏:Doe,电子邮件:nowhere@now
$array = array(
"name" => "John",
"surname" => "Doe",
"email" => "nowhere@nowhere.com"
);
通过使用内爆(“,”,$array)
,我得到如下结果:约翰,多伊,nowhere@nowhere.com 但是,我还需要将每个元素的键写入文件。
所需的输出如下:
姓名:约翰,姓氏:Doe,电子邮件:nowhere@nowhere.com
如何实现这一点?请尝试以下代码:
$csv = "";
foreach($array as $key => $data)
{
// be sure to add " in your csv
$csv .= '"'.$key.':'.$data.'",';
}
// and add a new line at the end
$csv .= "\n";
echo $csv;
$out = $sep = '';
foreach( $array as $key => $value ) {
$out .= $sep . $key . ':' . $value;
$sep = ',';
}
上面的答案在末尾输出一个尾随逗号。要更正此问题,我使用以下函数:
$array = array(
"name" => "John",
"surname" => "Doe",
"email" => "nowhere@nowhere.com"
);
function implodeKV($glueKV, $gluePair, $KVarray){
$t = array();
foreach($KVarray as $key=>$val) {
$t[] = $key . $glueKV . $val;
}
return implode($gluePair, $t);
}
echo implodeKV( ':' , ',' , $array);
// outputs name:John,surname:Doe,email:nowhere@nowhere.com
如果您使用的是PHP5.3+,那么匿名函数可以使代码更干净,尽管简单的for循环具有最好的性能。(使用
array\u walk
很接近!)
我使用几种不同的方法(使用PHP5.4.33)运行了一些测试:
函数makeArray(&$a){
$a=数组();
对于($i=0;$i<100000;$i++){
$a[rand()]=rand();
}
返回$a;
}
makeArray($array);
$before=微时间(真);
$result=内爆(
",",
数组映射(
功能($k,$v){
返回“$k:$v”;
},
数组_键($array),
$array
)
);
$after=微时间(真);
$dur=$after-$before;
echo“带匿名函数的数组映射:{$dur}s
”;
makeArray($array);
$before=微时间(真);
函数kv_func($k,$v){
返回“$k:$v”;
}
$result=内爆(
",",
数组映射(
“kv_func”,
数组_键($array),
$array
)
);
$after=微时间(真);
$dur=$after-$before;
echo“带函数的数组映射:{$dur}s
”;
makeArray($array);
$before=微时间(真);
步行街(
$array,
函数(&$v,$k){
$v=“$k:$v”;
}
);
$result=内爆(
",",
$array
);
$after=微时间(真);
$dur=$after-$before;
echo“带匿名函数的数组行走:{$dur}s
”;
makeArray($array);
$before=微时间(真);
$ff=真;
$sep=“,”;
$out=“”;
foreach($key=>$val的数组){
如果($ff)$ff=错误;
否则$out.=$sep;
$out.=“$key:$val”;
}
$after=微时间(真);
$dur=$after-$before;
echo“Foreach循环w/循环标志:{$dur}s
”;
makeArray($array);
$before=微时间(真);
$out=“”;
foreach($key=>$val的数组){
$out.=“$key:$val,”;
}
$out=substr($out,0,-1);
$after=微时间(真);
$dur=$after-$before;
echo“Foreach循环+substr:{$dur}s
”;
结果:
Array Map w/ anonymous function: 0.13117909431458s
Array Map w/ function: 0.13743591308594s // slower than anonymous
Array Walk w/ anonymous function: 0.065797805786133s // close second
Foreach loop w/ loop flag: 0.042901992797852s // fastest
Foreach loop + substr: 0.043946027755737s // comparable to the above
为了好玩,我尝试了for循环,但没有修改后面的逗号。它实际上没有产生任何影响:
Foreach loop w/ trailing comma: 0.044748067855835s
尝试或数组。这将在每个键值对之后添加一个换行符,这不是Jack所要求的。另外,这将在最后一个键值对之后留下一个尾随逗号。我非常喜欢您使用
$sep
的解决方案,以避免最后一个键值对之后出现尾随逗号的经典问题。
Foreach loop w/ trailing comma: 0.044748067855835s