I have a database table with the following schema and would like to update it correctly when a booking form is submitted with the correct matching ticket type and ticket values:
| listing_id | regular_ticket | _other_ticket[0][name] | _other_ticket[1][name] | regular_ticket_sold | _other_ticket[0][sold] | _other_ticket[1][sold] |
|---|---|---|---|---|---|---|
| 149 | regular-ticket | solo-ticket | group-ticket | 5 | 2 | 1 |
The array being posted after submitting the form could look like this(when buying all the ticket types):
{"listing_id":"149","date_start":"2023-04-28","date_end":"2023-04-28","tickets":[{"ticket":"regular-ticket","value":"1"},{"ticket":"solo-ticket","value":"1"},{"ticket":"group-ticket","value":"1"}]}
And like this when a user selects only one ticket type:
{"listing_id":"149","date_start":"2023-04-28","date_end":"2023-04-28","tickets":[{"ticket":"solo-ticket","value":"1"}]}
What I have tried:
// update tickets sold
function update_ticket_sold( $tickets, $listing_id )
{
$countable = array_column($tickets,'value'); //get ticket count from array
$other_tickets = get_post_meta( $listing_id, '_other_tickets', true);
if (!empty($tickets[0]['ticket']) && $tickets[0]['ticket'] == 'regular-ticket') {
//$tickets_count = (float) $countable[0];
$already_sold_tickets = (int) get_post_meta($listing_id,'regular_ticket_sold',true);
$sold_now = $already_sold_tickets + (float) $countable[0];
update_post_meta($listing_id,'regular_ticket_sold',$sold_now);
}
if(isset($other_tickets) && is_array(($other_tickets))){
$i = 0;
foreach ($other_tickets as $key => $ticket) {
if(in_array(($ticket['sold']),array_column($tickets,'sold'))) {
$column = '_other_tickets[][sold]';
$already_sold_tickets = (int) get_post_meta($listing_id,$column,true);
$sold_now = $already_sold_tickets + (float) $countable[$i];
update_post_meta($listing_id,$column,$sold_now);
$i++;
}
}
}
}
What I would like to achieve:
- regular_ticket ticket type to update values in regular_ticket_sold
- _other_ticket[0][name] ticket type should update value in _other_ticket[0][sold] and
- _other_ticket[1][name] to _other_ticket[1][sold]
When the regular ticket is selected, the functions updates the database correctly but when any of the other ticket types are selected they never get updated and I get Error: Warning: Undefined array key 1 and Warning: Undefined array key 2
I have been stuck for weeks with this problem. Kindly point me in the right way.