PHP、in_array 和数组中的快速搜索(最后) [英] PHP, in_array and fast searches (by the end) in arrays

查看:46
本文介绍了PHP、in_array 和数组中的快速搜索(最后)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我怀疑在数组中进行快速搜索的更好方法是什么(我说的是一个特定案例).

I have a doubt about what's the better way to make a fast search in arrays (I'm talking about an specific case).

假设我有一个数组 L = [A, B, C](当我开始时).当程序运行时,L 可能会增长(但到最后),我进行搜索的一种可能情况是 L = [A, B, C, D, E].

Supose that I have an array L = [A, B, C] (when I start). While the program is running, may be L will grow (but by the end), one possible case when I'll do the search is that L = [A, B, C, D, E].

事实是,当我搜索时,我想要查找的值可能只有 D 和 E.现在我使用的是 find_array(elem, array),但是这个函数不能被调整"来搜索从最后开始并减少索引,我害怕"对于所有搜索,函数 in_array 将检查所有具有较低索引的元素,然后才能找到我正在搜索的值.

The fact is that when I'm searching, the values that I want find could be only D and E. Now I'm using find_array(elem, array), but this function can't be "tweaked" to search starting at the end and decreasing the index, and I'm "afraid" that for all the searches the function in_array will examine all the elements with lower indexes before will find the value that I'm searching.

¿还有另一个搜索功能更适合我的问题吗?¿in_array 函数内部如何工作?

¿There is another search function wich fits better to my problem? ¿How works internally the in_array function?

提前致谢

推荐答案

我假设 in_array 是从 0 到 n-1 的线性搜索.

I assume that in_array is a linear search from 0 to n-1.

最快的搜索是将值存储为键并使用array_key_exists.

The fastest search will be to store the values as the keys and use array_key_exists.

$a['foo'] = true;
$a['bar'] = true;

if (array_key_exists('foo', $a)) ...

但如果这不是一个选项,您可以很容易地为索引数组创建自己的:

But if that's not an option, you can make your own for indexed arrays quite easily:

function in_array_i($needle, array $a, $i = 0);
{
  $c = count($a);
  for (;$i < $c; ++$i)
    if ($a[$i] == $needle) return true;
  return false;
}

它将从 $i 开始,您可以跟踪自己以跳过第一个元素.

It will start at $i, which you can keep track of yourself in order to skip the first elements.

或者……

function in_array_i($needle, array $a, $i = 0);
{
  return in_array($needle, $i ? array_slice($a, $i) : $a);
}

您可以进行基准测试,看看哪个更快.

You can benchmark to see which is faster.

这篇关于PHP、in_array 和数组中的快速搜索(最后)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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