基于键或数据的 PHP 查找
Key | Data
----------
1 | A
2 | B
3 | C
是否有一种数据结构允许我在给定密钥时查找数据,或者在给定数据时查找密钥?我正在使用 PHP,但我对任何语言的答案都很好奇。
Key | Data
----------
1 | A
2 | B
3 | C
Is there a data structure that allows me to lookup the data when given the key, or to lookup the key when given the data? I'm working in PHP, but I'm curious about answers for any language.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果你把它放在数组中..
If you have it in an array..
如果是PHP中的数组,并且想根据key获取数据,可以使用 array_key_exists() ,或者如果您想要基于数据的密钥,我认为您必须循环遍历数组
If it's an array in PHP, and you want to get the data based on the key, you can use array_key_exists() , or if you want the key based on the data, I think you'd have to loop over the array
在 PHP 中,您可以使用 数组 作为字典。
您的示例可以编码为:
In PHP you can use Arrays as dictionaries.
Your example could be coded as:
如果您使用键作为参考点,查找表将为您提供最佳性能。如果数据结构导致值引用,例如
in_array()
或array_search()
或任何完整数组扫描,则性能不会很好。通过
isset()
、key_exists()
、array_key_exists()
按键访问查找数据(在尝试访问之前检查其存在),否则空合并运算符将始终优于基于值的引用。对于
isset()
和 null 合并运算符,请注意,当访问的值为null
时,这些技术会将该值视为“未找到/设置”,因为它们看起来对于具有非空值的声明变量。代码:(演示)
输出:
A lookup table will offer you the best performance if you use keys as the reference point. If the data structure leads to value referencing such as
in_array()
orarray_search()
or any full array scan, this will not perform very well.Accessing the lookup data by key (checking its existence before trying to access it) via
isset()
,key_exists()
,array_key_exists()
, or the null coalescing operator will always outperform value-based referencing.With regard to
isset()
and the null coalescing operator, notice that when the value accessed isnull
, these technique treat the value as "not found/set" because they look for declared variables with non-null values.Code: (Demo)
Output: