PHP数组作为没有数组的索引

时间:2016-07-23 16:47:38

标签: php arrays types indices

我有一个PHP脚本,除了我收到此错误消息

之外,它的工作正常
Undefined index: Array in [...]/exp.php on line 239

在这一行上有这段代码:

$out_kostenstelle = $kostenstellen[$nextShift["kostenstelle"]][1].
    "(".$nextShift["kostenstelle"].")";

我认为数据作为索引的唯一部分是$nextShift["kostenstelle"]$kostenstellen的索引的部分。

然而,当我尝试使用此代码捕获此部分(它在一个循环中有数百次运行,因此我无法手动检查它)时,我的脚本永远不会进入if子句中的部分

if(is_array($nextShift["kostenstelle"]))
{
    echo "<pre>";
    var_dump($nextShift);
    echo "</pre>";
    die();
}

这对我没有任何意义,我尝试了很多东西。没有成功。

我认为这可能足以导致错误的代码,但以下是$kostenstellen$nextShift的结构

Kostenstellen:

array(2) {
  [100]=>
  array(2) {
    [0]=>
    string(3) "100"
    [1]=>
    string(11) "Company A"
  }
  [200]=>
  array(2) {
    [0]=>
    string(3) "300"
    [1]=>
    string(12) "Company B"
  }
}

和nextShift:

array(4) {
  ["id"]=>
  string(2) "168"
  ["start_unix"]=>
  string(10) "1466780000"
  ["end_unix"]=>
  string(10) "1466812400"
  ["kostenstelle"]=>
  string(3) "100"
}

1 个答案:

答案 0 :(得分:1)

没有办法解决它:问题是你尝试使用的索引本身就是一个数组。

当您在php $array[$index]中访问数组时,如果PHP不是字符串或数字,则会尝试对其进行字符串化。对数组进行字符串化可以得到文字"Array";就像你在这里一样。

然而,还有另一种可能性:当您运行循环时,数组已经字符串化。它意味着之前的某个地方,有人把它变成了一个字符串。

你可以检查是否有这样的:

if(is_array($nextShift["kostenstelle"]) || $nextShift["kostenstelle"] == "Array")
{
    echo "<pre>";
    var_dump($nextShift);
    echo "</pre>";
    die();
}
相关问题