Medoju Narendar
Medoju Narendar

Reputation: 185

How i can merge more than two Json strings in php

Below is my JSON strings like these, am trying to add jsons. How i can achieve.

$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"]}

I am trying to use this to merge them and am expecting output like below

   {
    "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"
            ]
        }
    ]
}

Any help?

Upvotes: 0

Views: 71

Answers (1)

splash58
splash58

Reputation: 26153

Decode json to php arrays, merge and encode back

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

echo json_encode($json1);

Upvotes: 4

Related Questions