1

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"
               ],
            ],
         }
      ],
5
  • php.net/manual/en/function.json-encode.php json_encode($rooms); Commented Jun 16, 2019 at 23:54
  • problem in php code. child and baby dates are not correct by field Commented Jun 16, 2019 at 23:59
  • 1
    Oh, that’s not what the question said. Your form does not appear to be set up to do multiple children or babies. You would have to name them something like child[$key][][child_date]. You have to send in the children as an array or you will only get the last one. Please edit your post to show the relevant parts of the form Commented Jun 17, 2019 at 1:54
  • thanks for your warning. I edited the question. $_POST['child_date'][][$key] not working Commented Jun 17, 2019 at 8:37
  • You’re right, it won’t work in the order you typed. And this I think is the question ... how do you order the indexes of a data structure. Once that falls in place, you’ll see how to craft the html form inputs and the json encoding is as easy as... putting it in the json_encode() command. I’ll put an answer together as soon as I have time Commented Jun 17, 2019 at 12:05

2 Answers 2

1

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 >
Sign up to request clarification or add additional context in comments.

9 Comments

thanks a lot. foreach. How do I create this loop with foreach?
Do you mean how to traverse $room?
Yes, to duplicate multiple rooms
If you set up your form names as illustrated, there's no need to iterate through it to copy it. Just copy $room. In practice, though, this structure is deeper than you would probably go; the room number would be a separate input and babies/children/adults would be their own arrays, and you'd only be inputting one room at a time from a form. But at any rate, this should give you insight into how to accomplish the task.
need to return with foreach because the number of rooms multiplied. room numbers not fixed
|
0

You can use the json_encode function like this:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.