2 回答
TA贡献1805条经验 获得超9个赞
如果不是仅仅使用像file_put_contents()你这样的东西写出数据,而是使用一些为 CSV 文件设计的方法,这将为你完成大部分工作......
要写入数据使用fputcsv(),这会转义分隔符(在这种情况下,“变为”)...
$row = ["894","Somebody","Related","2020-02-20",'{"name1":"value1","name2":"value2","name3":"value3"}',"expired"];
$fh = fopen($filepath, "a");
fputcsv($fh, $row);
fclose($fh);
这将写入文件
894,Somebody,Related,2020-02-20,"{""name1"":""value1"",""name2"":""value2"",""name3"":""value3""}",expired
然后从文件中读取,一次只读一行并使用fgetcsv()...
$fh = fopen($filepath, "r");
print_r(fgetcsv($fh)); // This in a loop to read all lines
fclose($fh);
这表明
Array
(
[0] => 894
[1] => Somebody
[2] => Related
[3] => 2020-02-20
[4] => {"name1":"value1","name2":"value2","name3":"value3"}
[5] => expired
)
TA贡献1911条经验 获得超7个赞
解决此问题的一种方法是创建数组的新副本并操作新数组并将 json 添加为原始数组的切片部分。
$allRows = array_map('str_getcsv',file($fp));
$new_arr = [];
foreach($allRows[0] as $key=>$item) {
$json = false;
if (substr($item,0,1) == '{') {
$json_start = $key;
$json = true;
}
if (substr($item,-2,2) == '}"') {
$json_stop = $key;
$json = true;
//Slice json-part from original array (in your case 4,5,6)
$sl = array_slice($allRows[0], $json_start, ($json_stop-$json_start)+1);
//Add the sliced part into key where json started
$new_arr[$json_start] = implode('',$sl);
}
if ($json === false) $new_arr[] = $item;
}
然后你在$new_arr.
- 2 回答
- 0 关注
- 164 浏览
添加回答
举报