phpcodeigniterdynamic-tables

How to use foreach inside foreach for dynamic fields php


I am having the following dynamically loaded values to be saved to DB

enter image description here

Here, what i need to save to the db is that if there are wo tickets form Adult, there should be two entries in the DB and if there are 3 tickets for child, need them in as three lines in the same db.

I have written the code as below

foreach ($ticket_description as $key => $value)
            {
                foreach ($tickets as $key2=> $value2) {

                        $tickets_data_array = array(

                            "ticket_description" => $ticket_description[$key2],
                            "price" => $price[$key2],
                        );
                        $this->db->insert('booked_tickets', $tickets_data_array);
                }
            }

I have taken VIP, Adult as seen above for "$ticket_description", number of tickets as "$tickets". The issue is I end up having multiple entries instead of 5 entries as above. Please help resolve this in php. I use codeigniter.


Solution

  • I think the issue is that you are looping over the both sets of description and keys in two loops, whereas you look as though you want to loop over the descriptions and the have an inner loop which is just for the number of tickets booked for that description.

    foreach ($ticket_description as $key=> $value) {
        // A plain for loop allows you to repeat the insert for the 
        // number of tickets
        for ($i = 0; $i < $tickets[$key]; $i++) {
            $tickets_data_array = array(
                // The description is also probably the value from the outer loop?
                "ticket_description" => $value,
                "price" => $price[$key],
            );
            $this->db->insert('booked_tickets', $tickets_data_array);
        }
    }