跳过数组的键无值foreach循环 [英] Skip keys in array without values in a foreach loop

查看:302
本文介绍了跳过数组的键无值foreach循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个正常的维数组,我们称之为 $ myarray中,用几个键,从[0]到[34]。某些键可以是空的,但。

I have a normal one dimensional array, let's call it $myarray, with several keys ranging from [0] to [34]. Some keys could be empty though.

假设我想在foreach循环使用这样的阵列

Suppose I want to use such array in a foreach loop

 $i = 1;
 $choices = array(array('text' => ' ', 'value' => ' '));
 foreach ( $myarray as $item ) :
      $count = $i++; 
      $choices[] = array('text' => $count, 'value' => $count, 'price' => $item);
 endforeach;

我希望在这个foreach循环跳过所有空键,因此其他的阵列我这里建造( $选择)可能行较小量超过 $ myArray的。与此同时,虽然,你看,我数着圈,因为我需要越来越多的新阵列的关键之一值正在兴建。该计数应该是渐进的(1..2..3..4 ...)。

I'd wish to skip in this foreach loop all the empty keys, therefore the other array I'm building here ($choices) could have a smaller amount of rows than $myarray. At the same time, though, as you see, I count the loops because I need an increasing number as value of one of the keys of the new array being built. The count should be progressive (1..2..3..4...).

感谢

推荐答案

array_filter() 将从数组中删除空元素

array_filter() will remove empty elements from an array

您也可以使用继续循环中跳过循环结构的其余部分并移动到下一个项目:

You can also use continue within a loop to skip the rest of the loop structure and move to the next item:

$array = array('foo', '', 'bar');

foreach($array as $value) {
  if (empty($value)) {
    continue;
  }

  echo $value . PHP_EOL;
}

// foo
// bar

这篇关于跳过数组的键无值foreach循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆