I'm decoding a JSON response and outputting it in a table. JSON response is separated in three elements (Events
, Organizers
and Venues
) and Events
nodes reference nodes from Venues
and Organizers
elements.
Here is an example of what print_r
displays for the JSON response:
Array
(
[Events] => Array
(
[0] => Array
(
[EventTitle] => Concert One
[Details] => Array
(
[VenueID] => 100
[EventDate] => 2016-01-01
)
)
[1] => Array
(
[EventTitle] => Concert Two
[Details] => Array
(
[VenueID] => 150
[EventDate] => 2016-01-02
)
)
)
[Venues] => Array
(
[0] => Array
(
[HallID] => 100
[VenueName] => Venue A
)
[1] => Array
(
[HallID] => 150
[VenueName] => Venue B
)
)
)
Actual JSON example looks like this:
{
"Events": [
{
"EventTitle": "Concert One",
"Details": {
"VenueID": 100,
"EventDate": "2016-01-01"
}
},
{
"EventTitle": "Concert Two",
"Details": {
"VenueID": 150,
"EventDate": "2016-01-02"
}
}
],
"Venues": [
{
"HallID": 100,
"VenueName": "Venue A"
},
{
"HallID": 150,
"VenueName": "Venue B"
}
]
}
Here is foreach loop that I use to create the table:
<?php
foreach($results['Events'] as $values)
{
echo '<tr><td>' . $values['EventTitle'] . '</td>';
echo '<td>' . $values['Details']['VenueID'] . '</td>';
echo '<td>' . $values['Details']['EventDate'] . '</td></tr>';
}
?>
It works well and creates a simple table:
Event title | Event venue | Event date
Concert One | 100 | 2016-01-01
Concert Two | 150 | 2016-01-02
What I'm struggling with is how to replace Venue ID
(100, 150) with VenueName
(Venue A, Venue B), so that the result is:
Event title | Event venue | Event date
Concert One | Venue A | 2016-01-01
Concert Two | Venue B | 2016-01-02
Is it possible to achieve this?
Try this:
foreach($results['Events'] as $values)
{
echo '<tr><td>' . $values['EventTitle'] . '</td>';
echo '<td>' . $results['Venues'][array_search($values['Details']['VenueID'], array_column($results['Venues'], 'HallID'))]['VenueName'] . '</td>';
echo '<td>' . $values['Details']['EventDate'] . '</td></tr>';
}
?>
Everything in one line!
What I would do is parse your Organizers
and Venue
into their own arrays, with the ID as the key. So you would have an array like this (where $arr
represents the variable holding the full array)
$venue = [];
foreach($arr['Venue'] as $vals) {
$venue[$vals['HallID']] = $vals['VenueName'];
}
You could build that with a foreach
loop. Then, you would iterate over your Events
, using the keys to get the correct relationship data (do the same thing to build $organizers
as $venue
)
foreach($results['Events'] as $values) {
echo '<tr><td>' . $values['EventTitle'] . '</td>';
echo '<td>' . $venue[$values['Details']['VenueID']] . '</td>';
echo '<td>' . $organizer[$values['Details']['OrganizerID']] . '</td>';
echo '<td>' . $values['Details']['EventDate'] . '</td></tr>';
}