[英]merge json file and a php array
大家好,我有一個像這樣的json文件:
[
{
"search":1,
"hotelId":"YYB",
"combination":"0|1|0|0|0|0",
},
{
"search":1,
"hotelId":"YYB",
"combination":"0|1|0|0|0|0",
},
{
"search":1,
"hotelId":"YYW",
"combination":"0|1|0|0|0|0",
}
]
我想向這個json添加一個數組php,轉換為json。
這是我的PHP數組
array(1) {
[0]=>
array(24) {
["search"]=>
int(1)
["hotelId"]=>
string(3) "rrr"
["combination"]=>
string(11) "0|1|0|0|0|0"
}
[1]=>
array(24) {
["search"]=>
int(1)
["hotelId"]=>
string(3) "ttt"
["combination"]=>
string(11) "0|1|0|0|0|0"
}
我試圖將我的編碼php數組添加到json文件。
這是我嘗試過的:
$filename = 'json_upload/rooms.json';
$result = fread($file2, filesize($filename));
$arr = $result;
$arr_ret_room = $room_arr; //my php array
$res = array_merge_recursive((array)$arr, (array)$arr_ret_room);
fwrite($file2, json_encode($res));
fclose($file2);
我也嘗試過用array_merge
打開json文件時結果不會改變,腳本為我添加了一個新的根元素,如下所示:
[
{
"search":1,
"hotelId":"YYB",
"combination":"0|1|0|0|0|0",
},
{
"search":1,
"hotelId":"YYB",
"combination":"0|1|0|0|0|0",
},
{
"search":1,
"hotelId":"YYW",
"combination":"0|1|0|0|0|0",
}
]
[
{
"search":1,
"hotelId":"rrr",
"combination":"0|1|0|0|0|0",
},
{
"search":1,
"hotelId":"ttt",
"combination":"0|1|0|0|0|0",
}
]
代替這個:
[
{
"search":1,
"hotelId":"YYB",
"combination":"0|1|0|0|0|0",
},
{
"search":1,
"hotelId":"YYB",
"combination":"0|1|0|0|0|0",
},
{
"search":1,
"hotelId":"YYW",
"combination":"0|1|0|0|0|0",
},
{
"search":1,
"hotelId":"rrr",
"combination":"0|1|0|0|0|0",
},
{
"search":1,
"hotelId":"ttt",
"combination":"0|1|0|0|0|0",
}
]
如何正確合並?
謝謝
如果我了解您正確的話:
// assuming that $file contains contents of json file
$arr = array(...); //your php array
$jsonArr = json_decode($file);
$result = $arr + $jsonArr;
那么您可以將$result
保存到文件中。
最好將JSON字符串轉換為數組,然后合並它們,而不是合並這些JSON字符串。 您需要更改此:
$arr = $result;
$arr_ret_room = $room_arr; //my php array
$res = array_merge_recursive((array)$arr, (array)$arr_ret_room);
fwrite($file2, json_encode($res));
fclose($file2);
至
$array1 = json_decode($result,true);
$array2 = $arr_ret_room;
$newArray = array_merge($array1,$array2);
$newJSON = json_encode($newArray);
fwrite($file2, $newJSON);
fclose($file2);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.