Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

json

arrays

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?

like image 414
Ethan Allen Avatar asked Feb 06 '23 03:02

Ethan Allen


2 Answers

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);
like image 124
Object Manipulator Avatar answered Feb 18 '23 05:02

Object Manipulator


Thats not json. its an array of objects

You can achieve what you want simply with

$json1[0]->fields = $json2;
like image 42
andrew Avatar answered Feb 18 '23 04:02

andrew