我有简单的JSON,如
[{
"id": "77",
"agent_id": "20",
"raised_by": "C",
"from_date": "2016-11-09",
"to_date": "2016-11-10",
"ConsultantInfo": {
"user_id": "3045",
"inquiry_id": "77"
},
"otherInfo": {
"a": "test",
"b": "testing"
}
}]
当我点击保存按钮的时候,我需要合并一些现有的json数据,如下所示,每当我点击保存按钮时会出现新数据,所以我必须将所有数据存储到json文件中阵列。
[{
"ConsultantInfo": {
"user_id": "1",
"inquiry_id": "2"
},
"otherInfo": {
"a": "abc",
"b": "xyz"
}
}]
所以最后的结果应该是这样的:
[{
"id": "77",
"agent_id": "20",
"raised_by": "C",
"from_date": "2016-11-09",
"to_date": "2016-11-10",
"ConsultantInfo": [
{
"user_id": "3045",
"inquiry_id": "77"
},
{
"user_id": "2",
"inquiry_id": "71"
}
],
"otherInfo": [
{
"a": "test",
"b": "testing"
},
{
"a": "kk",
"b": "dd"
}
]
}]
mycode的:
<?php
$state_current_arr = '{ "id": "77", "agent_id": "20", "raised_by": "C", "from_date": "2016-11-09", "to_date": "2016-11-10" }';
if(isset($_POST['savebtn'])) //save button
{
$jsonData = array();
$jsonData['ConsultantInfo'] = array("user_id"=>"3045","inquiry_id"=>"77");
$jsonData['otherInfo'] = array("a"=>"test","b"=>"testing");
$tempArray = json_decode($state_current_arr,true);
$tempArray = array_merge($tempArray, $jsonData);
$jsonData_merged = json_encode($tempArray);
echo $jsonData_merged;
}
?>
答案 0 :(得分:1)
您可以使用array_merge_recursive
,但需要将ConsultantInfo
和otherInfo
修改为多维数组
试试这个:
$state_current_arr = '{ "id": "77", "agent_id": "20", "raised_by": "C", "from_date": "2016-11-09", "to_date": "2016-11-10" }';
$jsonData = array();
$jsonData['ConsultantInfo'][] = array("user_id"=>"3045","inquiry_id"=>"77");
$jsonData['otherInfo'][] = array("a"=>"test","b"=>"testing");
$tempArray = json_decode($state_current_arr,true);
$dataRequired = array();
$dataRequired['ConsultantInfo'][] = array("user_id"=>"1","inquiry_id"=>"2");
$dataRequired['otherInfo'][] = array("a"=>"abc","b"=>"xyz");
$jsonData_merged = array_merge_recursive($tempArray,$jsonData,$dataRequired);
var_dump($jsonData_merged);