搜索数组:array_filter vs循环

Pit*_*ger 2 php arrays multidimensional-array

我真的是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 
      ) 
    )
  )
)
Run Code Online (Sandbox Code Playgroud)

我正在这样搜索。

$thisQuestion = array_filter($pollQuestions, function($q) {
  return questionId == $q["id"];
});
Run Code Online (Sandbox Code Playgroud)

小智 7

我知道,这个问题很旧,但是我不同意接受的答案。我还想知道,foreach()循环和array_filter()函数之间是否有区别,发现了以下内容:

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

Levi Jackson做得很好,比较了几个循环和array_*()函数的速度。据他介绍,foreach()循环比array_filter()函数快。尽管它几乎没有什么大的区别,但是当您必须处理大量数据时,它就变得很重要。


nic*_*ick 7

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


小智 7

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

但实际上这是真的。另一个有趣的结果是 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
**/

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;
Run Code Online (Sandbox Code Playgroud)


Sub*_*ger -5

数组过滤器

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

至于我也一样。

  • 这不是OP问的。 (7认同)