Ethan Allen Ethan Allen - 2 months ago 13
JSON Question

How do I add a JSON array to existing JSON in PHP?

I have the following...

$json1
:

[{
"id": 1,
"table_prefix": "movie",
"display_name": "Movies"
}]


$json2
:

[{
"field_name": "Title",
"column_name": "title",
"sort_order": 0,
"sort_section": 0,
"required": 1,
"relationship": "field",
"table_type": "",
"view_type": "text",
"description": "",
"multi_value": 0,
"char_count": 255
}, {
"field_name": "Synopsis",
"column_name": "synopsis",
"sort_order": 1,
"sort_section": 0,
"required": 0,
"relationship": "field",
"table_type": "",
"view_type": "longtext",
"description": "",
"multi_value": 0,
"char_count": 10000
}]


What I want is for
$finalJSON
to look like this:

[{
"id": 1,
"table_prefix": "movie",
"display_name": "Movies",
"fields": [{
"field_name": "Title",
"column_name": "title",
"sort_order": 0,
"sort_section": 0,
"required": 1,
"relationship": "field",
"table_type": "",
"view_type": "text",
"description": "",
"multi_value": 0,
"char_count": 255
}, {
"field_name": "Synopsis",
"column_name": "synopsis",
"sort_order": 1,
"sort_section": 0,
"required": 0,
"relationship": "field",
"table_type": "",
"view_type": "longtext",
"description": "",
"multi_value": 0,
"char_count": 10000
}]
}]


Is there a simple PHP JSON function to allow me to attach a JSON array to existing JSON like this?

Answer

The idea is to need to convert the JSON to array using json_decode, manipulate the fields, and encode it back in JSON format.

Try this:

$decoded_json = json_decode($json1, true);
$decoded_json[0]['fields'] = json_decode($json2, true);
$finalJSON = json_encode($decoded_json, JSON_PRETTY_PRINT);
Comments