处理键值中包含句点的数组
我正在从数组中获取数据。由于某种原因,该数组具有像 [3.3]
这样的键值,我无法从中检索数据。
我有这个数组 [3.3] =>名字 [3.6] =>姓氏[2] => [电子邮件受保护]
。
当我尝试调用 $array[3.3]
时,它返回 null,但是当我调用 $array[2]
时,我会收到电子邮件。有什么想法吗?
I'm getting data from an array. For some reason the array has key values like [3.3]
which I'm having trouble retrieving data from.
I have this array [3.3] => First Name [3.6] => Last Name[2] => [email protected]
.
When I try to call $array[3.3]
it returns null, but when I call $array[2]
I am given the e-mail. Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
引用键值时使用单引号(基本上将其视为字符串,PHP 可能就是这样做的)
Use single quotes when referencing the key value (basically treat it like a string, that's what PHP is probably doing)
来自 php 手册:
所以你试图获取不存在的 $array[3] ,所以你得到 Null
From php manual :
So you're trying to get $array[3] which does not exist, so you get Null
http://php.net/manual/en/language.types.array.php 浮点数总是会被截断为整数(例如 3.3 总是被数组解释为 3) 我想知道你的数组是否期望一个字符串而不是浮点数。您是否尝试过 $array["3.3"] 而不是 $array[3.3] ?
Since a float would always get truncated as an integer (e.g. 3.3 would always be interpreted by the array as 3) I wonder if your array is expecting a String not a float. Have you tried $array["3.3"] instead of $array[3.3]?
我猜它与 PHP autocasting 3.3 有关 =>浮动
尝试 $array['3.3']
I guess it has something todo with the PHP autocasting 3.3 => float
try $array['3.3']
所以输出这段代码:
将是:
So output this code:
would be:
当使用浮动键将元素添加到数组中时,我遇到了类似的问题 - PHP 正在覆盖现有值(键 1.2 被 1.5 等覆盖)。
基于这个SO线程,我将转换键添加到字符串中:
I had a similar problem when adding elements into array using float keys - PHP was overwriting existing values (key 1.2 was overwritten by 1.5 etc.).
Based on this SO thread I add cast key to string: