array_slice but for images php

落爺英雄遲暮 提交于 2020-01-03 04:28:07

问题


i have written this code

  <?php
        $a = Meme::all();
        $b = count($a);
        for($i=$b;$i<$b-3;$i--)  {
    ?>      <div class="col-sm-6"><img class="lazy" data-src="<?php echo $a[$i]->path; ?>" /> </div>
    <?php
    }?> 

i want to output the last 3 memes(images) but this for loop doesn't work. So i found something that is called array_slice and i wanted to use it but everyone was using print_r but in this case i don't need it. So any suggestions?


回答1:


Store those 3 elements of array $a in a new array $b by using array_slice:

<?php    
    $a = Meme::all();
    $b = array_slice($a, 3);

    for ($i = 0; $i < 3; $i++){
?>
    <div class="col-sm-6"><img class="lazy" data-src="<?php echo $b[$i]->path; ?>" /> </div>
<?php
    }
?>



回答2:


It is as easy as this :

$nb = 3;

$a = [1 => 'foo', 2 => 'bar', 3 => 'john', 4 => 'doe', 5 => 'test'];
$b = count($a);
$results = array_slice($a, $b-$nb, $nb);

foreach($result AS $k => $result) {
    echo '<p>'.$result.'</p>';
}

Also see this snippet here in action.

Explanations : You use array_slice with first param being your array. The second if the offset, i.e. the starting key of your array.




回答3:


FWIW I have provided another alternative:

<?php
$a = Meme::all();
$b = count($a);
$toShow = 3; // how many elements to display

for ($i = $b - $toShow; $i < $b; $i++) { ?>
    <div class="col-sm-6"><img class="lazy" data-src="<?php echo $a[$i]->path; ?>" /></div>
<?php } ?>

It is slightly faster than the accepted solution.
Something else to note is that if the array is not a multiple of 3 then the corrected solution will throw an error since the splice will not return an array with the length of 3. Naturally, if $toShow is greater than or equal to the count($a) this will also throw an error.



来源:https://stackoverflow.com/questions/46727672/array-slice-but-for-images-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!