【问题标题】:while loop optimization a little bitwhile 循环优化一点
【发布时间】:2023-03-18 06:56:01
【问题描述】:

我正在运行一个 while 循环,它会抓取我网站上的所有帖子

while ( $all_query->have_posts() ) : $all_query->the_post();

我需要玩的每一个都有元数据。这是一个名为'rate' 的字段,我需要合并类似的值,1-5。

目前,我有这个

while ( $all_query->have_posts() ) : $all_query->the_post();
    $fives = 0;
    $fours = 0;
    $threes = 0;
    $twos = 0;
    $ones = 0;
    if(get_post_meta($post->ID, 'rate', true) == 'five') { 
        $fives = $fives + 5;
    }
    if(get_post_meta($post->ID, 'rate', true) == 'four') { 
        $fours = $fours + 4;
    }
    if(get_post_meta($post->ID, 'rate', true) == 'three') { 
        $threes = $threes + 3;
    }
    if(get_post_meta($post->ID, 'rate', true) == 'two') { 
        $twos = $twos + 2;
    }
    if(get_post_meta($post->ID, 'rate', true) == 'one') { 
        $ones = $ones + 1;
    }
    endwhile;

它有效,但它真的很恶心。

有没有更优化和更干净的方法来做这样的事情?

【问题讨论】:

  • 听起来像是 switch 的工作。
  • 您是否要平均费率?
  • @Supericy - 基本上,是的。我曾经做 5 个单独的循环,但那变得非常昂贵。因此,我试图将其全部压缩为 1 个循环并从一个循环中操作变量以使用

标签: php loops while-loop micro-optimization


【解决方案1】:

一点点数组操作可以大大简化这个:

$counts = array_fill(1, 5, 0);
$labels = array(1 => 'one', 'two', 'three', 'four', 'five');

while(...) {
    $index = array_search(get_post_meta($post->ID, 'rate', true), $labels);
    $counts[$index] += $index;
}

总数保存在$counts 中,$counts[1] 是总数。 $labels 可以帮助将文本表示与$counts 中的数组位置相匹配——这当然可以用普通的switch 来代替。

循环使用array_search 将文本表示转换为数组索引,然后简单地将相应的计数增加一个等于索引的数量。

生产代码当然也应该考虑array_search返回false的可能性。

【讨论】:

  • 啊哈!我的好先生,你真是太棒了。这很好用!稍微调整一下,它就可以出色地工作了,而且比我以前的干净多了!谢谢!! :)
猜你喜欢
  • 1970-01-01
  • 2016-03-18
  • 2011-05-14
  • 2020-06-24
  • 2018-03-01
  • 2019-02-19
  • 2018-11-24
  • 2012-06-12
  • 2017-01-07
相关资源
最近更新 更多