有人可以帮我把数据添加到以下json。
$temp='{
"custId": 123,
"data": [
{
"code": "abc1"
},
{
"code": "abc2"
}
],
"id": 102
}';
要添加的数据
$data1='{
"code": "abc3"
}';
期望的结果
$temp='{
"custId": 123,
"data": [
{
"code": "abc1"
},
{
"code": "abc2"
},
{
"code": "abc3"
}
],
"id": 10
}';
我可以将数据附加到$ temp,但有人可以帮助用PHP将数据添加到特定位置。先感谢您。 (我已尝试过json_decode($ temp,true),然后找到要添加data1但失败的位置。)
答案 0 :(得分:3)
您可以将数据转换为普通的PHP数组:
$array = json_decode($temp, true);
然后只需添加或更改您想要的任何内容:
$array["data"][] = array(["code"] => "abc3");
并重新编码为json:
$temp = json_encode($array);// encode to json
答案 1 :(得分:1)
首先,您需要将JSON转换为PHP数组,如下所示:
$array = json_decode($temp, true);
然后,它就像:
一样简单$array['data']['code'] = 'abc3';
如果要添加的字符串仍然是JSON,则必须在数组中转换该字符串,以便:
$arr_to_add = json_decode($data1, true);
$array['data'][] = $arr_to_add;
最后,当然,再次编码如下:
$final_json = json_encode($array);
希望这有帮助! :d
答案 2 :(得分:0)
json_decode
解码json。这将返回一个PHP变量。json_encode
获取带有新值的json。返回包含JSON的字符串。答案 3 :(得分:0)
你可以试试这个:
<?php
$temp='{
"custId": 123,
"data": [
{
"code": "abc1"
},
{
"code": "abc2"
}
],
"id": 102
}';
$data1='{
"code": "abc3"
}';
$jarr=json_decode($temp,true);
$appArr=json_decode($data1,true);
$desire=array_merge($jarr,$appArr);
//print_r($desire);
echo json_encode($desire);