0
我從DB中存儲的形式值與json_encode()
,我需要將這些值插入.csv
文件。 這裏是我的代碼:將JSON編碼數組中的內部數組插入到csv文件與PHP
$con=mysqli_connect("localhost","db_user","db_pass","table_name");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_set_charset($con,"utf8");
$sql = $con->prepare("SELECT message FROM online_survey");
$sql->execute();
$array = [];
foreach ($sql->get_result() as $row){
$array[] = json_decode($row['message'], true);
}
if (!$sql) {
die(mysqli_error($con));
}
$fp = fopen('/path/to/file.csv', 'w');
foreach($array as $key) {
fputcsv($fp, $key);
}
fclose($fp);
而在這個文件我正在從這種形式的所有值除了數組。 例如:
Cell 1 Cell2 Cell3 Cell4 Cell5 Cell6 Cell7 OrgName Country City Position Scope Array
我需要的是讓這樣的:
Array
(
[organization_name] => orgName
[organisation_country] => Country
[organisation_city] => City
[organization_position] => position
[other_1_4_text] =>
[organisation_scope] => Local
[activity_areas] => Public finance management, Democratic participation and civil society, Urban development and management, Anti-corruption organisations and institutions, Children and youth
)
取而代之的是:
Array
(
[organization_name] => orgName
[organisation_country] => Country
[organisation_city] => City
[organization_position] => position
[other_1_4_text] =>
[organisation_scope] => Local
[activity_areas] => Array
(
[0] => Public finance management
[1] => Democratic participation and civil society
[2] => Urban development and management
[3] => Anti-corruption organisations and institutions
[4] => Children and youth
)
...
)
如果您需要了解更多信息,請讓我知道!
謝謝!
關於第二個'foreach'您可以轉儲var'var_dump($ key)'來檢查發生了什麼。 –
@MichalPrzybylowicz更新! –
檢查密鑰上的is_array並使用print_r(key,true)將其返回。 – Paul