我如何在php中合并两个以上的Json字符串

时间:2017-05-02 20:30:46

标签: php json merge

下面是我的JSON字符串,我试图添加jsons。我怎么能实现。

$json1 = {"properties":{"title":"test","labels":["JanActual","Jan","Goal"],"values":["0","10000","0"]}}
$json2 = {"key":"Rental","type":"bar","values":["0","10000","0"]}
$json3 = {"key":"Service","type":"bar","values":["189","30000","0"]}

我正在尝试使用它来合并它们,我期待输出如下

   {
    "properties":{
        "title":"test",
        "labels":[
            "JanActual",
            "Jan",
            "Goal"
        ],
        "values":[
            "0",
            "10000",
            "0"
        ]
    },
    "data": [
        {
            "key":"Rental",
            "type":"bar",
            "values":[
            "0",
            "10000",
            "0"
            ]
        },
        {
            "key":"Service",
            "type":"bar",
            "values":[
                "189",
                "30000",
                "0"
            ]
        }
    ]
}

任何帮助?

1 个答案:

答案 0 :(得分:4)

将json解码为php数组,合并并编码回来

$json1 = json_decode($json1, true);
$json1['data'] = array(
  json_decode($json2, true),
  json_decode($json3, true)
);

echo json_encode($json1);