J smith J smith - 3 months ago 15
PHP Question

Grouping by sub arrays

I have the following array:

$tickets[] = array( 'event_id', 'ticket_name','holder_name', 'order_id', 'ticket_id', 'security_code')


I want to be able to group the output by the
'event_id'
and get:

Event_ID 1
-> Ticket ID 1 ......
-> Ticket ID 2 .....
Event_ID 2
-> Ticket ID 3......


I have got this so far:

foreach ($tickets as $key => $event ) {
$tickets[$key]['event_id'] = $event;


Does this look correct?

Thanks

Edit: Integrated solution 1.

`

<?php
do_action( 'tribe_tickets_ticket_email_top' );
$groupedEvents = array();
foreach($tickets as $key => $ticket)
{
$groupedEvents['Event_ID_'.$ticket['event_id']][] = $ticket['ticket_id'];

if ( function_exists( 'tribe_get_venue_id' ) ) {
$event = get_post( $groupedEvents['Event_ID'] );
$venue_id = tribe_get_venue_id( $event->ID );
if ( ! empty( $venue_id ) ) {
$venue = get_post( $venue_id );
}
$venue_label = tribe_get_venue_label_singular();
$venue_name = $venue_phone = $venue_address = $venue_city = $venue_web = '';
if ( ! empty( $venue ) ) {
$venue_name = $venue->post_title;
$venue_phone = get_post_meta( $venue_id, '_VenuePhone', true );
$venue_address = get_post_meta( $venue_id, '_VenueAddress', true );
$venue_city = get_post_meta( $venue_id, '_VenueCity', true );
$venue_web = get_post_meta( $venue_id, '_VenueURL', true );
}

}

<?php echo $venue_name; ?>
<?php echo $venue_address; ?>
<?php echo $venue_city; ?>
<?php echo $venue_phone; ?>
<a href="<?php echo esc_url( $venue_web ) ?>" ><?php echo $venue_web; ?></a>
}
<?php esc_html_e( 'Ticket #', 'event-tickets' ); ?> <?php echo $groupedEvents['ticket_id']; ?>
<?php esc_html_e( 'Ticket Type', 'event-tickets' ); ?>
<?php echo $groupedEvents['ticket_name']; ?>
<?php echo $groupedEvents['holder_name']; ?>
<?php esc_html_e( 'Security Code', 'event-tickets' ); ?>
<?php echo $groupedEvents['security_code']; ?>
?>`

Answer

You can group event ticket id's as given in the following code, just make a new array and push ticket id into the corresponding event id in the array...

$tickets = array( 
                    0=> array( 'event_id'=>1,'ticket_name'=>'a','holder_name'=>'w','ticket_id'=>11),
                    1=> array( 'event_id'=>2,'ticket_name'=>'b','holder_name'=>'x','ticket_id'=>22),
                    2=> array( 'event_id'=>1,'ticket_name'=>'c','holder_name'=>'y','ticket_id'=>33),
                    3=> array( 'event_id'=>2,'ticket_name'=>'d','holder_name'=>'z','ticket_id'=>44)
                );

$groupedEvents = array();               
foreach($tickets as $key => $ticket)
{
    $groupedEvents['Event_ID_'.$ticket['event_id']][] = $ticket['ticket_id'];
}               
echo "<pre>"; print_r($groupedEvents);

This will give you :

Array
(
    [Event_ID_1] => Array
        (
            [0] => 11
            [1] => 33
        )

    [Event_ID_2] => Array
        (
            [0] => 22
            [1] => 44
        )

)

If any question just comment, I'll be there ...