0

I'm using file_get_contents() to parse data of a JSON file within a foreach() loop onto my page.

<?php

    $url = 'data/gigs.json';
    $data = file_get_contents($url);
    $gigs = json_decode($data, true);

    foreach ($gigs as $gig) {
        echo '<tr>';
        echo '<td><time>' . $gig['date'] . '</time></td>';
        echo '<td>' . $gig['event_venue'] . '</td>';
        echo '<td>' . $gig['location'] . '</td>';
        echo '<td><a class="btn btn-primary external" href="' . $gig['tickets_url'] . '">Buy</a></td>';
        echo '</tr>';
    }

?>

This works fine and I also want to parse this data onto the homepage, but this time I only want to parse let's say the first 5 records of the JSON array. I do know how to parse the first 5 individually, but not within this foreach loop. I tried Google for an answer, but probably used the wrong query :)

1
Contributor
1
Reply
25
Views
3 Months
Discussion Span
Last Post by gentlemedia
1

I figured this one out myself. There is a array_slice(), so I've added this to my foreach()and voila.

<?php

    $url = 'data/gigs.json';
    $data = file_get_contents($url);
    $gigs = json_decode($data, true);

    foreach (array_slice($gigs,0,5) as $gig) {
        echo '<tr>';
        echo '<td><time>' . $gig['date'] . '</time></td>';
        echo '<td>' . $gig['event_venue'] . '</td>';
        echo '<td>' . $gig['location'] . '</td>';
        if (empty($gig['tickets_url'])) {
            echo '<td></td>';
        } else {
            echo '<td><a class="btn btn-primary external" href="' . $gig['tickets_url'] . '">Buy</a></td>';
        }
        echo '</tr>';
    }

?>

Edited by gentlemedia

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.