大家好,只是想问我如何将关联数组放入 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);