Anuj TBE
Anuj TBE

Reputation: 9800

SQL join two tables to give multi array result

I have 2 table events and categories. categories table has 2 columns id and category. The event table contains category_idas foreign key of categories table.

Now the content of events table is given by

+------------------------------------------------------+
| id | category_id | event_name | event_date | created |
+------------------------------------------------------+
| 1  |     1       | event 1    | 12-04-2016 |TIMESTAMP|
| 2  |     1       | event 2    | 14-04-2016 |TIMESTAMP|
| 3  |     2       | event 1    | 16-04-2016 |TIMESTAMP|
| 4  |     1       | event 3    | 14-04-2016 |TIMESTAMP|
| 5  |     2       | event 2    | 12-04-2016 |TIMESTAMP|
+------------------------------------------------------+

Now what I want to do is to select all rows and produce output in the form

=> Category 1
     <> event 1
     <><> 12-04-2016
     <> event 2
     <><> 14-04-2016
     <> event 3
     <><> 14-04-2016
=> Category 2
     <> event 1
     <><> 16-04-2016
     <> event 2
     <><> 12-04-2016

How it can be done. I am using PHP and mysqli and I want to store this information in PHP array so that I could print it anywhere in page using PHP for loop or foreach

Upvotes: 0

Views: 2321

Answers (1)

Alexander Worton
Alexander Worton

Reputation: 91

Sort the query by category, event name

SELECT  categories.category,
        events.event_name

FROM categories

    LEFT JOIN events
    ON events.category_id = categories.id

ORDER BY categories.category, events.event_name

then iterate through the result to construct the multi-dimensional array you want:

$data = array();

foreach($results as $row){
    $data[$row['category']][$row['event_name']]['event_name'] = $row['event_name'];
    $data[$row['category']][$row['event_name']]['event_date'] = $row['event_date'];
}

you can then perform a nested iteration something like this to output:

foreach($data as $category => $events){

    echo $category.'<br>';

    foreach($events as $event){
        echo '    <> '.$event['event_name'].'<br>';
        echo '        <> '.$event['event_date'].'<br>';
    }

}

Rather than using the event / category names as indexes for the multidimensional array, you could grab the event id and use that instead if the names aren't unique.

Upvotes: 2

Related Questions