组合:避免多重嵌套的foreach [英] combinations: avoiding multiple nested foreach

查看:95
本文介绍了组合:避免多重嵌套的foreach的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



示例代码:


$ b当您需要检查/组合数组元素时,如何避免嵌套foreach? $ b

  $ as = array($ optionA1,$ optionA2)
$ bs = array($ optionB1,$ optionB2)
$ cs = array($ optionC1,$ optionC2)

foreach($ as as $ a){
foreach($ bs as $ b){
foreach($ cs as $ c){
$ result = $ this->方法($ a,$ b,$ c); ($结果)等



$ c $

$ b $
b

任何有可以避免嵌套的替代方法的人都可以编写自己的Iterator类来实现 href =http://php.net/manual/en/class.iterator.php =noreferrer>迭代器接口。然后你可以让它的构造函数接受三个数组,然后你可以用foreach循环每个组合。

不过,我认为这会明显变慢,所以我会避免它。知道你想要避免嵌套的foreach循环的原因是很有意思的。

When you need to check/have combinations of array elements, how can you avoid nesting foreach?

Example code:

$as = array($optionA1, $optionA2)
$bs = array($optionB1, $optionB2)
$cs = array($optionC1, $optionC2)

foreach ($as as $a) {
    foreach ($bs as $b) {
      foreach ($cs as $c) {
          $result = $this->method($a, $b, $c);
          if ($result) etc
      }
    }
}

Anyone with alternative approaches that can avoid nesting?

解决方案

You could write your own Iterator class which implements the Iterator interface. You could then have its constructor accept the three arrays and then you can use it to loop over every combination with foreach.

However I think this would be significantly slower, so I would avoid it. It would be interesting to know the reasons you want to avoid the nested foreach loops?

这篇关于组合:避免多重嵌套的foreach的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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