简体   繁体   中英

php how to loop through array until condition is met?

I have a database table with images that I need to display. In my view, I'd like to display UP TO 10 images for each result called up. I have set up an array with the 20 images that are available as a maximum for each result (some results will only have a few images, or even none at all). So I need a loop that tests to see if the array value is empty and if it is, to move onto the next value, until it gets 10 results, or it gets to the end of the array.

What I'm thinking I need to do is build myself a 2nd array out of the results of the test, and then use that array to execute a regular loop to display my images. Something like

<?php 
  $p=array($img1, $img2.....$img20);

  for($i=0; $i<= count($p); $i++) {
    if(!empty($i[$p])) {
    ...code
    }
  }
?>

How do I tell it to store the array values that aren't empty into a new array?

you could do something like:

$imgs = array(); $imgs_count = 0;
foreach ( $p as $img ) {
    if ( !empty($img) ) {
        $imgs[] = $img;
        $imgs_count++;
    }
    if ( $imgs_count === 10 ) break;
}

You can simply call array_filter() to get only the non-empty elements from the array. array_filter() can take a callback function to determine what to remove, but in this case empty() will evaluate as FALSE and no callback is needed. Any value that evaluates empty() == TRUE will simply be removed.

$p=array($img1, $img2.....$img20);
$nonempty = array_filter($p);

// $nonempty contains only the non-empty elements.

// Now dow something with the non-empty array:
foreach ($nonempty as $value) {
   something();
}

// Or use the first 10 values of $nonempty
// I don't like this solution much....
$i = 0;
foreach ($nonempty as $key=>$value) {
  // do something with $nonempty[$key];
  $i++;
  if ($i >= 10) break;
}

// OR, it could be done with array_values() to make sequential array keys:
// This is a little nicer...
$nonempty = array_values($nonempty);
for ($i = 0; $i<10; $i++) {
   // Bail out if we already read to the end...
   if (!isset($nonempty[$i]) break;

   // do something with $nonempty[$i]
}
$new_array[] = $p[$i];

$p[$i]存储到$new_array的下一个元素中(又名array_push() )。

Have you thought about limiting your results in the sql query?

select * from image where img != '' limit 10

This way you are always given up to 10 results that are not empty.

ẁhile循环可能就是您正在寻找的http://php.net/manual/en/control-structures.while.php

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM