大家好,我想问一下如何在csv中放一个关联数组? 例如,如果我有这样的数组。
Array
(
[0] => Array
(
[restaurant_id] => 1227
[new_lat] => 13.62241
[new_long] => 123.19341
[date_updated] => 2013-11-14 11:20:26
)
[1] => Array
(
[restaurant_id] => 1218
[new_lat] => 14.66732
[new_long] => 121.02618
[date_updated] => 2013-11-14 11:22:22
)
)
我生成csv的代码是:
$restaurant_id = $post_data['company_id'];
$new_lat_entry = $post_data['new_lat'];
$new_long_entry = $post_data['new_long'];
$data_add = array(
'restaurant_id' => $restaurant_id,
'new_lat' => $new_lat_entry,
'new_long' => $new_long_entry,
'date_updated' => date('Y-m-d H:i:s')
);
$data = unserialize(file_get_contents('addresses.txt'));
$data[] = $data_add;
$serialize_data = serialize($data);
file_put_contents("addresses.txt", $serialize_data, LOCK_EX); //write the text file
$array = unserialize(file_get_contents('addresses.txt')); //THIS WILL GET THE ARRAY
echo "<pre>";
print_r($array); //display it
$csv = '';
foreach($array as $row) {
$csv .= implode(',', $row) . "\n";
}
//fn_print_die($csv);
$file_input = fopen("addresses.csv","w");
foreach($csv as $line){
fputcsv($file_input,split(',',$line));
}
fclose($file_input);
答案 0 :(得分:8)
这应该有用......
<?php
foreach ($array as $row) {
fputcsv($file_input, $row);
}
fclose($file_input);
?>
请参阅php.net上的fputcsv手册
答案 1 :(得分:4)
您应尽可能尝试实施SPL classes:
$csv_file = new SplFileObject('addresses.csv', 'w');
foreach ($address_list as $address_fields) {
$csv_file->fputcsv($address_fields);
}
答案 2 :(得分:2)
您可以使用implode轻松地执行此类操作
$csv = '';
foreach($array as $row) {
$csv .= implode(',', $row) . "\n";
}
答案 3 :(得分:2)
要使其清洁,您必须
原因很简单:餐厅 A 有&#34; [self_service] =&gt;真&#34; 餐厅 B 的CSV行要么会错过一个列,要么更糟糕,有&#34; [vegetarian_food] =&gt;假&#34;代替。
最后,你会有&#34; true&#34;和&#34;假&#34;在彼此相同的列中,以第一个含义&#34;是,自助服务&#34;和第二个意思&#34;对不起蔬菜&#34;。您可能永远不会注意到,因为它们可能仍然具有相同的计数(数组)。
(我会把它写成评论,但我的Stack Exchange声誉还不允许我这样做(48现在,还有2个去,是的!)