0

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.

Big Fish
  • 5
  • 1
  • 5
  • 4
    Possible duplicate of [Find the last element of an array while using a foreach loop in PHP](http://stackoverflow.com/questions/665135/find-the-last-element-of-an-array-while-using-a-foreach-loop-in-php) – Reda Maachi Mar 21 '17 at 13:04
  • 2
    `array_pop`, `array_pop` – u_mulder Mar 21 '17 at 13:04

4 Answers4

1

Yes, there is a way.

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

Have a try.

Marcel
  • 4,854
  • 1
  • 14
  • 24
0

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

Reda Maachi
  • 853
  • 6
  • 15
0

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;
}
Ollie in PGH
  • 2,559
  • 2
  • 16
  • 19
0

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
u_mulder
  • 54,101
  • 5
  • 48
  • 64