从阵列中选择每第n项 [英] Selecting every nth item from an array

查看:105
本文介绍了从阵列中选择每第n项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是最有效的方式从大阵选择每n个项目?有没有一种智能的方式来做到这一点,或者循环的唯一途径?

What would be the most efficient way to select every nth item from a large array? Is there a 'smart' way to do it or is looping the only way?

几点考虑:


  • 该阵列是130 000项
  • 相当大
  • 我必须选择每个项目205

  • 的项目不是数字索引,所以为($ i = 0; $ I< = 130000; $ I + = 205)将无法正常工作

  • The array is quite large with 130 000 items
  • I have to select every 205th item
  • The items are not numerically indexed, so for($i = 0; $i <= 130000; $i += 205) won't work

到目前为止,这是最有效的方法,我想出了:

So far, this is the most efficient method I've come up with:

$result = array();
$i = 0;
foreach($source as $value) {

    if($i >= 205) {
        $i = 0;
    }

    if($i == 0) {
        $result[] = $value;
    }

    $i++;
}

或用模一样的:

$result = array();
$i = 0;
foreach($source as $value) {
    if($i % 205 == 0) {
        $result[] = $value;
    }
    $i++;
}

这些方法可能很慢,有什么办法改善?或者,我只是鸡蛋里挑骨头吗?

These methods can be quite slow, is there any way to improve? Or am I just splitting hairs here?

修改

好的答案周围的所有适当的解释,试图挑选最合适作为接受的答案。谢谢!

Good answers all around with proper explanations, tried to pick the most fitting as the accepted answer. Thanks!

推荐答案

一个foreach循环提供对您根据对比测试大阵最快的迭代。我会类似于你所拥有的,除非有人希望解决的循环展开

A foreach loop provides the fastest iteration over your large array based on comparison testing. I'd stick with something similar to what you have unless somebody wishes to solve the problem with loop unrolling.

这答案应该运行速度更快。

This answer should run quicker.

$result = array();
$i = 0;
foreach($source as $value) {
    if ($i++ % 205 == 0) {
        $result[] = $value;
    }
}

我没有时间来测试,但您可能能够使用@哈伊姆的解决方案,如果你第一数字索引数组的变化。这是值得一试,看看你是否能收到过我的previous解决方案的任何收益:

I don't have time to test, but you might be able to use a variation of @haim's solution if you first numerically index the array. It's worth trying to see if you can receive any gains over my previous solution:

$result = array();
$source = array_values($source);
$count = count($source);
for($i = 0; $i < $count; $i += 205) {
    $result[] = $source[$i];
}

这将在很大程度上取决于如何优化功能array_values​​的。它可以很好的执行可怕

This would largely depend on how optimized the function array_values is. It could very well perform horribly.

这篇关于从阵列中选择每第n项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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