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 :)

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>';
    }

?>
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.