0

I have to comunicate with some API which expect JSON. Until now I was fine because I needed just simple json so I just create array like this:

$data = array (
    "firstName" => "TEXT1",
    "lastName" => "TEXT2",
    "license" => "TEXT3",
    "password" => "TEXT4",
    "username" => "TEXT5"
);

And after that just simple

$data_string = json_encode($data);

So final JSON looks like:

{
    "firstName": "TEXT1",
    "lastName": "TEXT2",
    "license": "TEXT3",
    "password": "TEXT4",
    "username": "TEXT5"
}

However now I have to change it a bit and I am confuse, my new JSON shoud looks like:

{
    "contact": {
        "city": "New Yourk",
        "email": "my@mail.com",
        "phone": "777888999",
        "postCode": "07101",
        "street": "Street N. 12"
    },
    "enabled": true,
    "firstName": "Robert",
    "lastName": "Exer",
    "username": "login@login.com",
    "license": "text",
    "password": "text"
}

As you can see it is basicly just added contact part. I was thinking how I can do this but only think I found was something like to insert array to existing $data array and then json_encode this but this will not give me a contract: at start.

Of course there is possible to do it some other way like create one json and then another and hardly connect string and so on. But i believe there have to be some better way how to do things like this.

I apprciate any advise:)

Andurit
  • 5,612
  • 14
  • 69
  • 121

2 Answers2

4

Just put an array in the value of contact:

$data = array(
    'contact' => array(
        'city' => 'New York',
        'email' => 'my@mail.com',
        //...
    ),
    'enabled' => true,
    'firstName' => 'Robert',
    'lastName' => 'Exer',
    //...
);

$data_string = json_encode($data);
ulentini
  • 2,413
  • 1
  • 14
  • 26
Barmar
  • 741,623
  • 53
  • 500
  • 612
4

An array can contain another array, which will be encoded as a separate object inside the previous object:

$data = array (
    "contact" => array(
        "city" => "New Yourk",
        "email" => "my@mail.com",
        "phone" => "777888999",
        "postCode" => "07101",
        "street" => "Street N. 12"
    ),
    "enabled": true,
    .. etc
);
MatsLindh
  • 49,529
  • 4
  • 53
  • 84
  • 1
    Thank you, THUMB UP for this answer. However to be Fair Barmar was a few sec before you so I mark his answer as correct :) Thanks again – Andurit Dec 30 '15 at 14:09