对于Unicode数组的替代方法

huangapple go评论76阅读模式
英文:

alternative to in_array for unicode arrays

问题

in_array函数在处理大数组时非常慢,因为它进行线性搜索。

一个更快的替代方法是搜索数组的键。

因此,对于大数组来说,

if (isset($array[$val]))

if (in_array($val,$array))

要快得多。

然而,如果使用Unicode作为数组键将不起作用。

是否有一种替代方法可以在不使用类似in_array或array_search这样的线性搜索或生成像md5这样的哈希值的情况下实现这一点?

英文:

The in_array function is very slow for large arrays due to doing a linear search.

A faster alternative is to search the key of the array.

Thus

if (isset($array[$val]))

is much faster than

if (in_array($val,$array))

for large arrays. However using unicode as array keys will not work.

Is there an alternative way to do this for unicode without resorting to linear searches such as in_array or array_search or generating hashes like md5?

答案1

得分: 2

可以使用任何可以转换为字符串的内容作为键。

参考:https://stackoverflow.com/questions/10696067/characters-allowed-in-php-array-keys

但显然,有些人在其数组键中使用特殊字符时可能会遇到问题。我敢打赌,如果您在存储键时使用不同的编码,而在搜索时使用硬编码的 Iso 编码 PHP 脚本搜索键,可能会出现这种情况。这只是一个例子,有数十种类似的情景。
为了确保始终使用相同的编码,我建议使用rawurlencode

英文:

You can use anything as key which can be converted into a string.

Compare: https://stackoverflow.com/questions/10696067/characters-allowed-in-php-array-keys

But nevertheless apparently some poeple have problems with special characters in their array-keys. I bet this may be the case if you use different encodings at the time you store the key and when you search for it. For example your keys come from a database using UTF-8, but when you search you have the key you search for hardcoded in a Iso-encoded PHP-script. This is just an example, there are dozens of scenarios like this.
To ensure you always use the same encoding I would use rawurlencode.

huangapple
  • 本文由 发表于 2020年1月3日 15:52:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/59574985.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定