【问题标题】:Why array_key_exists() on array of array doesn't work properly?为什么数组数组上的array_key_exists() 不能正常工作?
【发布时间】:2013-07-16 23:55:19
【问题描述】:

我在 php 中有一个数组数组。两个数组都没有索引(它们使用键)。

 $this->confArr["$sectionName"] = Array(); // case 1

这返回真:

 isset($this->confArr["$sectionName"]);

因为已经设置了一个名为 $sectionName 的元素。

 $this->confArr["$sectionName"]["$itemKey"] = $itemValue; //case 2

我不知道为什么,但这总是返回 FALSE

 array_key_exists($itemKey, $this->confArr["$sectionName"]);

有什么问题?

【问题讨论】:

  • $sectionName$itemKey 真的设置了吗?
  • 如果$itemValuenull(或者如果你没有给它一个值)那么isset 将返回false。是吗?
  • 打印 confArr["$sectionName"]["$itemKey"];在判断之前
  • isset() 检查该值是否已设置且不为空。 $itemValue 返回什么
  • @ClaudioFerraro:很可能您至少在这些断言中的一个中是错误的。如果一切都是这样,你会得到true。虽然isset 可能存在错误并且您是第一个发现它的人,但这种可能性极小。

标签: php


【解决方案1】:

问题是这样的:

array_key_exists($itemKey, $this->confArr["$sectionName"]);

应该是:

array_key_exists("$itemKey", $this->confArr["$sectionName"]);

不知道确切原因,但它是这样工作的?

【讨论】:

  • PHP 甚至不区分数字字符串和整数键...将该键隐式转换为字符串不会产生影响除非有些东西我们没有知道,像 $itemKey 持有类似 SimpleXML 对象的东西,它响应__toString()
  • 我刚刚用 PHP 5.3.15 和$itemKey=42 测试了它。两者都返回 1。你需要告诉我们$itemKey 持有什么。
  • 那...可能意味着$itemkey 不是一个标量,但有一些方法可以转换成一个(__toString() 等)?我们想知道,注意展示var_dump($itemKey); 产生了什么?
猜你喜欢
  • 2014-08-27
  • 1970-01-01
  • 1970-01-01
  • 2015-08-10
  • 2016-05-05
  • 2017-03-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多