大家好我有一个像这样的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",
}
]
如何正确合并?
由于
答案 0 :(得分:0)
如果我理解你的错误:
// assuming that $file contains contents of json file
$arr = array(...); //your php array
$jsonArr = json_decode($file);
$result = $arr + $jsonArr;
然后您可以将$result
保存到您的文件中。
答案 1 :(得分:0)
将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);