I am having the following dynamically loaded values to be saved to DB
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.
2
Answers
Your embedded loop is logically incompatible with the outer loop, because you loop all description in the outer loop and embed a loop over all ticket entries in the inner loop and you insert them all.
For example, if you have 5 ticket entries and 3 possible descriptions, then you loop each description and then loop all 5 tickets inside each description, inserting all ticket entries as many times as many possible descriptions you have, whereas you wanted to insert the ticket entries each exactly once with the correct description.
Hence, embedding the ticket loop inside the description loop is superfluous and redundant and you need a single loop instead:
Note that you can get the price and the description for each item with the help of your
$ticket_description
and$price
arrays.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.