2 回答

TA貢獻(xiàn)1805條經(jīng)驗(yàn) 獲得超9個(gè)贊
如果不是僅僅使用像file_put_contents()你這樣的東西寫出數(shù)據(jù),而是使用一些為 CSV 文件設(shè)計(jì)的方法,這將為你完成大部分工作......
要寫入數(shù)據(jù)使用fputcsv(),這會轉(zhuǎn)義分隔符(在這種情況下,“變?yōu)椤保?..
$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貢獻(xiàn)1911條經(jīng)驗(yàn) 獲得超7個(gè)贊
解決此問題的一種方法是創(chuàng)建數(shù)組的新副本并操作新數(shù)組并將 json 添加為原始數(shù)組的切片部分。
$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 關(guān)注
- 218 瀏覽
添加回答
舉報(bào)