【问题标题】:PHP Foreach , WherePHP Foreach , 在哪里
【发布时间】:2023-04-02 04:15:01
【问题描述】:

有没有办法在 PHP 的 foreach 方程中添加 where 类。

目前我正在像这样向 foreach 添加一个 if。

<?php foreach($themes as $theme){
    if($theme['section'] == 'headcontent'){
       //Something
    }
}?>


<?php foreach($themes as $theme){
    if($theme['section'] == 'main content'){
       //Something
    }
}?>

大概 PHP 必须遍历每个结果的所有结果。有没有更有效的方法来做到这一点。像

foreach($themes as $theme where $theme['section'] == 'headcontent')

这个可以吗

【问题讨论】:

  • 您可以在 foreach 循环之前过滤数组,因此首先过滤“headcontent”,然后循环。但我认为你不会从中获得任何好处。
  • 你每次都运行两个循环吗?我们在那些if-statements 中谈论了多少代码?两种情况下的内容是相似还是完全不同?
  • 我不明白,当你已经达到一定的价值时,你会追求什么

标签: php loops foreach where


【解决方案1】:

“foreach-where”与“foreach-if”完全相同,因为无论如何 PHP 必须遍历所有项目以检查条件。

可以写在一行,体现“哪里”的精神:

foreach ($themes as $theme) if ($theme['section'] == 'headcontent') {
    // Something
}

这实际上与问题末尾建议的构造相同;你可以用同样的方式阅读/理解它。

然而,它并没有解决这样一个事实,即在问题的特定场景中,使用任何类型的“foreach-where”构造都会有效地循环遍历所有项目多次。答案在于将所有测试和相应的处理重新组合到一个循环中。

【讨论】:

  • 这是我问题的完美答案,谢谢。
  • 虽然我的 PHP 代码 linter 根本不喜欢这个。
【解决方案2】:

使用 SWITCH 声明。

 <?php
    foreach($themes as $theme)
      {
        switch($theme['section'])
        {
            case 'headcontent':
                //do something
                break;
            case 'main content':
                //do something
                break;
        }
       }
    ?>

【讨论】:

    【解决方案3】:

    你最好使用for loop 来做类似的事情

    <?php 
        $cnt = count($themes);
        for($i = 0;$i < $cnt,$themes[$i]['section'] == 'headcontent' ;$i++){
    
        }
    ?>
    

    【讨论】:

    • 为什么?或者使用 foreach 和参考...增益?
    • 参考..??会怎样
    • 为什么要使用 for 循环呢? ...foreach($themes as &amp;$theme):至少会避免再次将数组“复制”到内存中,并且应该几乎与 for 循环一样快。但是你的“方式”看起来也很酷;)[据我所知===== 快]
    【解决方案4】:

    如果有人使用 MVC 框架,“foreach where”的答案就在这里

    <?php foreach ($plans as $plan) if ($plan['type'] == 'upgrade'): ?>
    
        // Your code here
    
    <?php endif; ?>
    

    记住endif;之后不需要endforeach;声明

    如果有人想在endif;endforeach; 之间写更多代码,那么上面应该是:

    <?php foreach ($plans as $plan): if ($plan['type'] == 'upgrade'): ?>
    
        // Your code here
    
    <?php endif; ?>
    
        // More of your code
    
    <?php endforeach; ?>
    

    【讨论】:

      猜你喜欢
      • 2016-06-01
      • 2018-02-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多