繁体   English   中英

PHP如何遍历数组直到满足条件?

[英]php how to loop through array until condition is met?

我有一个数据库表,其中包含需要显示的图像。 我认为,每个调用的结果最多显示10张图像。 我设置了一个数组,其中包含20个图像,每个结果最多可使用20个图像(某些结果将只有几个图像,甚至根本没有)。 因此,我需要一个循环来测试数组值是否为空以及是否为空,然后移动到下一个值,直到获得10个结果,或者到达数组末尾为止。

我想做的是根据测试结果构建第二个数组,然后使用该数组执行常规循环以显示我的图像。 就像是

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

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

我如何告诉它将不为空的数组值存储到新数组中?

您可以执行以下操作:

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

您可以简单地调用array_filter()以仅从数组中获取非空元素。 array_filter()可以使用回调函数来确定要删除的内容,但是在这种情况下, empty()值为FALSE并且不需要回调。 任何计算为empty() == TRUE都将被删除。

$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() )。

您是否考虑过限制SQL查询中的结果?

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

这样,您总是可以得到最多10个非空的结果。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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