Big Fish
Big Fish

Reputation: 5

Get last two items of json_decode results with PHP

The following code works and pulls all the images in from the json file.

    $content = file_get_contents('URL');
    $json = json_decode($content, true);

    foreach($json['format'] as $item) {
            echo '<img src="' . $item['picture'] . '">';
    }

Is there a way that I can have it only grab the last two pictures.

Upvotes: 0

Views: 625

Answers (4)

u_mulder
u_mulder

Reputation: 54841

My version using array_pop:

$content = file_get_contents('URL');
$json = json_decode($content, true); 

// take last element of array, array reduces by 1 element
$last = array_pop($json['format']);
print_r($last);

// take last element of array again, array reduces by 1 element
$last = array_pop($json['format']);
print_r($last);

// Beware - using `$json['format']` later means that 
// you use array without two last elements

Upvotes: 0

Ollie in PGH
Ollie in PGH

Reputation: 2629

You can reverse the order of the array, run it backwards in your foreach loop, grab the first two then break.

$reversed = array_reverse($json);
$counter = 0;
foreach ($reversed['format'] as $item) {
    if ($counter == 2) {
          break;
     }
     //your echo image code
++$counter;
}

Upvotes: 0

Reda Maachi
Reda Maachi

Reputation: 857

Use this:

$numItems = count(foreach($json['format']);
$i = 0;
foreach($json['format'] as $item) {
  if(++$i === $numItems-1) {
    result1 = $json['format'][$i]
    echo "first picture!";
  } if(++$i === $numItems) {
    result2 = $json['format'][$i]
    echo "second picture!";
  }
}    

And result1 and result2 is your pictures

Upvotes: 0

Marcel
Marcel

Reputation: 5119

Yes, there is a way.

$result = array_slice($json['format'], -2);

Have a try.

Upvotes: 1

Related Questions