Tamer
Tamer

Reputation: 33

Creating nested json with php

How can I convert the data I send with post to php code? I have 3 select fields. adult, child, baby. I want to create the following json structure up to the number of rooms when I post. The number of children and babies is not correct by area. How can I do it?

foreach ($this->input->post('adult') as $key => $value) {
    $rooms[] = array(
        'adult' => $_POST['adult'][$key],
        'child' => array(
            'child_total' => $_POST['child'][$key],
            'child_date' => $_POST['child_date']
        ),
        'baby' => array(
            'baby_total' => $_POST['baby'][$key],
            'baby_date' => null
        )
    );
}

I want to this json...

rooms: [
         {
            adult: 2,
            child: [
               child_total: 1
               child_date: [
                   "2017-08-10"
               ],
            ],
            baby: [
               baby_total: 1
               baby_date: [
                   "2017-07-01"
               ],
            ],
         },
         {
            adult: 1,
            child: [
               child_total: 2
               child_date: [
                   "2017-08-08",
                   "2017-08-09"
               ],
            ],
            baby: [
               baby_total: 2
               baby_date: [
                   "2017-06-08",
                   "2017-05-09"
               ],
            ],
         }
      ],

Upvotes: 1

Views: 183

Answers (2)

Tim Morton
Tim Morton

Reputation: 2644

To figure out the data structure needed to make you json encoded string, let's start by defining the objects you're working with. Assuming this is something like a hotel booking system, let's map it out:

A hotel has rooms. They are identified by room number. This can be illustrated in code by $room[$room_number]. Using the room number as the key allows you to uniquely identify a particular room.

Each room has occupants: adults, children, and babies. This can be illustrated in code by

$room[$room_number]['adults']
$room[$room_number]['children']
$room[$room_number]['babies']

The set of babies can be illustrated as $baby[]. We really don't need to identify the baby with a unique identifier other that the index number; we're just interested in the list.

So, let's replace ['babies'] with ['baby'][]

$room[$room_number]['adults']
$room[$room_number]['children']
$room[$room_number]['baby'][]

Each baby has attributes. We're only going to use one, but for the sake of example, let's say we want to record two: birthdate and name. Another way of saying that would be each $baby = array('birthday'=>$birthdate, 'name'=>$name);

This is a little harder to illustrate, since you have to gather all the babies information before you assign it to $room[$room_number]['baby'][]. So I will show it using the index number:

$room[$room_number]['adults']
$room[$room_number]['children']
$room[$room_number]['baby'][0]['birthdate']
$room[$room_number]['baby'][0]['name']

The same functionality is desired for children:

$room[$room_number]['adults']
$room[$room_number]['children'][0]['birthdate']
$room[$room_number]['children'][0]['name']
$room[$room_number]['baby'][0]['birthdate']
$room[$room_number]['baby'][0]['name']

See a pattern? [identifier][attribute][identifier][attribute]

With this data structure, we can build your html inputs, assuming 2 children and 2 babies:

<?php
// assuming room number is 123
$room_number = '123';

?>
<!-- child 1 name -->
<label><input name="room[<?= $room_number ?>]['child'][0]['name']">Child 1 name</label>
<!-- child 1 birthdate -->
<label><input name="room[<?= $room_number ?>]['child'][0]['birthdate']">Child 1 birthdate</label>


<!-- child 2 name -->
<label><input name="room[<?= $room_number ?>]['child'][1]['name']">Child 2 name</label>
<!-- child 2 birthdate -->
<label><input name="room[<?= $room_number ?>]['child'][1]['birthdate']">Child 2 birthdate</label>

When you receive these inputs in your php script, it will already be properly formed as an array (I'm excluding adults and filled in sample values):

php > $room_number='123';
php > $room[$room_number]['child'][0]['birthdate'] = '20010-01-01';
php > $room[$room_number]['child'][0]['name'] ='Junior';
php > $room[$room_number]['child'][1]['birthdate'] = '2019-01-01';
php > $room[$room_number]['child'][1]['name'] = 'Bubba';
php > print_r($room);
Array
(
    [123] => Array
        (
            [child] => Array
                (
                    [0] => Array
                        (
                            [birthdate] => 20010-01-01
                            [name] => Junior
                        )

                    [1] => Array
                        (
                            [birthdate] => 2019-01-01
                            [name] => Bubba
                        )

                )

        )

)

This can easily be fed into json_encode: print json_encode($room);

However, you might ask what about the counts (totals)?

Those can easily be figured from the array structure, so they don't really need to be included:

php > print count($room[$room_number]['child']);
2
php >

Upvotes: 1

Carlos Espinoza
Carlos Espinoza

Reputation: 1175

You can use the json_encode function like this:

json_encode(['rooms' => $rooms])

Upvotes: 0

Related Questions