使用PHP中的键与数组内爆

Jac*_*ill 0 php csv arrays

我需要在PHP中将数组写入.csv文件.

示例数组:

$array = array(
    "name" => "John",
    "surname" => "Doe",
    "email" => "nowhere@nowhere.com"
);
Run Code Online (Sandbox Code Playgroud)

通过使用implode(",", $array),我得到这样的结果:
John,Doe,nowhere@nowhere.com

但是,我还需要将每个元素的键写入文件.

所需的输出是这样的:
name:John,surname:Doe,email:nowhere@nowhere.com

我怎么做到这一点?

Mar*_*ski 11

试试这段代码:

$out = $sep = '';
foreach( $array as $key => $value ) {
    $out .= $sep . $key . ':' . $value;
    $sep = ',';
}
Run Code Online (Sandbox Code Playgroud)

  • 我真的很喜欢用'$ sep`解决你的解决方案,以避免在最终的键值对之后出现尾随逗号的经典问题. (7认同)