Hi all I have a json file like this:
[
{
"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",
}
]
And I want to add to this json an array php converted into a json.
This is my php array
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"
}
I'm trying to add my encode php array to the json file.
This is what I have tried:
$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);
I have also tried with array_merge
the result doesn't change when I open the json file the script add me a new root element like this:
[
{
"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",
}
]
Instead of this:
[
{
"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",
}
]
How can I merge correctly?
Thanks
If I understand you correct:
// assuming that $file contains contents of json file
$arr = array(...); //your php array
$jsonArr = json_decode($file);
$result = $arr + $jsonArr;
then you can save your $result
to your file.
It's better to convert JSON string to array then merge them instead of combining these JSON string. You need to change this:
$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);
to
$array1 = json_decode($result,true);
$array2 = $arr_ret_room;
$newArray = array_merge($array1,$array2);
$newJSON = json_encode($newArray);
fwrite($file2, $newJSON);
fclose($file2);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.