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