搜索数组:array_filter 与循环

发布于 2024-11-25 20:09:35 字数 857 浏览 2 评论 0原文

我是 PHP 新手,需要有关数组搜索的建议。

如果我想搜索多维数组内的元素,我可以使用 array_filter ,也可以循环遍历数组并查看是否存在与我的条件匹配的元素。

我在很多地方都看到这两个建议。哪个更快?下面是一个示例数组。

Array ( 
  [0] => Array ( 
    [id] => 4e288306a74848.46724799
    [question] => Which city is capital of New York?
    [answers] => Array ( 
      [0] => Array ( 
        [id] => 4e288b637072c6.27436568 
        [answer] => New York 
        [question_id_fk] => 4e288306a74848.46724799 
        [correct] => 0 
      ) 
      [1] => Array ( 
        [id] => 4e288b63709a24.35955656 
        [answer] => Albany 
        [question_id_fk] => 4e288306a74848.46724799 
        [correct] => 1 
      ) 
    )
  )
)

我正在这样寻找。

$thisQuestion = array_filter($pollQuestions, function($q) {
  return questionId == $q["id"];
});

I am really new in PHP and need a suggestion about array search.

If I want to search for an element inside a multidimensional array, I can either use array_filter or I can loop through the array and see if an element matching my criteria is present.

I see both suggestion at many places. Which is faster? Below is a sample array.

Array ( 
  [0] => Array ( 
    [id] => 4e288306a74848.46724799
    [question] => Which city is capital of New York?
    [answers] => Array ( 
      [0] => Array ( 
        [id] => 4e288b637072c6.27436568 
        [answer] => New York 
        [question_id_fk] => 4e288306a74848.46724799 
        [correct] => 0 
      ) 
      [1] => Array ( 
        [id] => 4e288b63709a24.35955656 
        [answer] => Albany 
        [question_id_fk] => 4e288306a74848.46724799 
        [correct] => 1 
      ) 
    )
  )
)

I am searching like this.

$thisQuestion = array_filter($pollQuestions, function($q) {
  return questionId == $q["id"];
});

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

随波逐流 2024-12-02 20:09:35

我知道,这个问题很老了,但我不同意公认的答案。我还想知道 foreach() 循环和 array_filter() 函数之间是否存在差异,并发现以下帖子:

http://www.levijackson.net/are-array_-functions-faster-than-loops/< /a>

(存档:https://web.archive.org/web/20200930002558/https://www.levijackson.net/are-array_-functions-faster-than-loops/

李维杰克逊做得很好并比较了几个循环和 array_*() 函数的速度。根据他的说法,foreach() 循环比 array_filter() 函数更快。虽然它通常不会产生这么大的差异,但当您必须处理大量数据时,它就开始变得重要了。

I know, the question is old, but I disagree with the accepted answer. I was also wondering, if there was a difference between a foreach() loop and the array_filter() function and found the following post:

http://www.levijackson.net/are-array_-functions-faster-than-loops/

(archive: https://web.archive.org/web/20200930002558/https://www.levijackson.net/are-array_-functions-faster-than-loops/)

Levi Jackson did a nice job and compared the speed of several loop and array_*() functions. According to him a foreach() loop is faster than the array_filter() function. Although it mostly doesn't make such a big difference, it starts to matter, when you have to process a lot of data.

弥繁 2024-12-02 20:09:35

我制作了一个测试脚本,因为我有点怀疑......内部函数怎么会比循环慢......

但实际上这是真的。另一个有趣的结果是 php 7.4 几乎比 7.2 快 10 倍!

你可以自己尝试一下

<?php
/*** Results on my machine ***
php 7.2
array_filter: 2.5147440433502
foreach: 0.13733291625977
for i: 0.24090600013733

php 7.4
array_filter: 0.057109117507935
foreach: 0.021071910858154
for i: 0.027867078781128

php 8.2
array_filter: 0.069692134857178
foreach: 0.018320083618164
for i: 0.019519329071045
**/

ini_set('memory_limit', '500M');
$data = range(0, 1000000);

// ARRAY FILTER
$start = microtime(true);
$newData = array_filter($data, function ($item) {
    return $item % 2;
});
$end = microtime(true);

echo "array_filter: ";
echo $end - $start . PHP_EOL;

// FOREACH
$start = microtime(true);
$newData = array();
foreach ($data as $item) {
    if ($item % 2) {
        $newData[] = $item;
    }
}
$end = microtime(true);

echo "foreach: ";
echo $end - $start . PHP_EOL;

// FOR
$start = microtime(true);
$newData = array();
$numItems = count($data);
for ($i = 0; $i < $numItems; $i++) {
    if ($data[$i] % 2) {
        $newData[] = $data[$i];
    }
}
$end = microtime(true);

echo "for i: ";
echo $end - $start . PHP_EOL;

I've made a test script because I was a little skeptical ...how can an internal function be slower than a loop...

But actually it's true. Another interesting result is that php 7.4 is almost 10x faster than 7.2!

You can try yourself

<?php
/*** Results on my machine ***
php 7.2
array_filter: 2.5147440433502
foreach: 0.13733291625977
for i: 0.24090600013733

php 7.4
array_filter: 0.057109117507935
foreach: 0.021071910858154
for i: 0.027867078781128

php 8.2
array_filter: 0.069692134857178
foreach: 0.018320083618164
for i: 0.019519329071045
**/

ini_set('memory_limit', '500M');
$data = range(0, 1000000);

// ARRAY FILTER
$start = microtime(true);
$newData = array_filter($data, function ($item) {
    return $item % 2;
});
$end = microtime(true);

echo "array_filter: ";
echo $end - $start . PHP_EOL;

// FOREACH
$start = microtime(true);
$newData = array();
foreach ($data as $item) {
    if ($item % 2) {
        $newData[] = $item;
    }
}
$end = microtime(true);

echo "foreach: ";
echo $end - $start . PHP_EOL;

// FOR
$start = microtime(true);
$newData = array();
$numItems = count($data);
for ($i = 0; $i < $numItems; $i++) {
    if ($data[$i] % 2) {
        $newData[] = $data[$i];
    }
}
$end = microtime(true);

echo "for i: ";
echo $end - $start . PHP_EOL;
遗失的美好 2024-12-02 20:09:35

我知道这是一个老问题,但我要说两点:对我来说,使用 foreach 循环比使用 array_filter 快得多。使用foreach,按id执行搜索需要1.4秒,使用过滤器需要8.6秒。

I know it's an old question, but I'll give my two cents: for me, using a foreach loop was much faster than using array_filter. Using foreach, it took 1.4 seconds to perform a search by id, and using the filter it took 8.6 seconds.

神爱温柔 2024-12-02 20:09:35

根据我自己的经验,foreach 更快。我认为这与函数调用开销、参数检查、复制到变量返回指令等有关。当使用基本语法时,解析的代码更有可能更接近编译/解释的字节码,有更好的优化核心。

共同的规则是:任何事情都更简单,运行更快(意味着更少的检查,更少的功能,只要它有你需要的一切)

From my own experience, foreach is faster. I think it has something to do with function call overhead, arguments check, copy to variable return instruction, etc.. When using a basic syntax, the parsed code is more likely to be closer to the compiled/interpreted bytecodes, have better optimization down the core.

The common rule is : anything is simplier, run faster (imply less check, less functionnality, as long as it has all you need)

り繁华旳梦境 2024-12-02 20:09:35

Array_Filter

迭代输入数组中的每个值,将它们传递给
回调函数。如果回调函数返回true,则当前
输入的值返回到结果数组中。数组键是
保留。

至于我也一样。

Array_Filter

Iterates over each value in the input array passing them to the
callback function. If the callback function returns true, the current
value from input is returned into the result array. Array keys are
preserved.

as for me same.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文