【问题标题】:PHP Array Undefined index error issues even when I can see the array output即使我可以看到数组输出,PHP Array Undefined index 也会出现错误问题
【发布时间】:2020-02-24 23:37:29
【问题描述】:

我有一个数字索引数组,这里是print_r的一部分:

Array
(
    [0] => Array
        (
            [from_stop_id] => 1
            [to_stop_id] => 1
            [transfer_type] => 1
            [min_transfer_time] => 
        )

    [1] => Array
        (
            [from_stop_id] => 3
            [to_stop_id] => 3
            [transfer_type] => 1
            [min_transfer_time] => 
        )

    [2] => Array
        (
            [from_stop_id] => 4
            [to_stop_id] => 4
            [transfer_type] => 1
            [min_transfer_time] => 
        )
)

这是我的 php 循环:

for ( $counter = 0; $counter < count($transfers_csv); $counter++) {
    echo $transfers_csv[$counter]['from_stop_id'];
    echo $transfers_csv[$counter]['to_stop_id'];
    echo  $transfers_csv[$counter]['transfer_type']; 
    echo $transfers_csv[$counter]['min_transfer_time'];
}

这是我的错误输出:

Notice: Undefined index: from_stop_id in C:\MAMP\htdocs\wp50\wp-content\plugins\tm-gtfs-data\tm-gtfs-data.php on line 453
11
Notice: Undefined index: from_stop_id in C:\MAMP\htdocs\wp50\wp-content\plugins\tm-gtfs-data\tm-gtfs-data.php on line 453
31
Notice: Undefined index: from_stop_id in C:\MAMP\htdocs\wp50\wp-content\plugins\tm-gtfs-data\tm-gtfs-data.php on line 453
41

当我知道以下内容时,我无法理解为什么它会给我一个未定义的索引。 $transfers_csv 是一个数字索引数组。 我可以从输出中看到“from_stop_id”、“to_stop_id”和“transfer_type”的值,但“min_transfer_type”的值为空或 NULL。

有人看到我在这里做错了吗??

【问题讨论】:

  • 您确定密钥 11、31 和 41 存在吗?为什么不让它变得简单并使用foreach? here is a portion of the print_r 将该示例扩展到过去的键 12。
  • 您是否尝试过 var_dumping $transfers_csv[$counter] 以确保它保存您期望的数据?
  • @trey 你的意思是$transfers_csv? $counter 是 for 循环的整数
  • @Andreas nah,$transfers_csv[$counter] 应该显示一个带有键 == 计数器的数组 - 不过,正如您所说,如果在这里使用 foreach 会更容易(对于每个人)^ ^

标签: php arrays


【解决方案1】:

您显然是从 csv 文件中读取标题,并且错误地在第一个标题 from_stop_id 中包含了 BOM(字节顺序标记)

所以from_stop_id 实际上是\uFEFFfrom_stop_id这就是 PHP 抛出未定义索引通知的原因

在此处了解更多信息:https://en.wikipedia.org/wiki/Byte_order_mark

不确定您是否使用fgetscsv(),但已知此函数在处理 BOM 时会出现问题。

如果您可以控制 csv 文件,则可以在不包含 BOM 的情况下保存它。

也可以在您的代码上处理这个问题,一种方法是:

$fp = fopen($path, 'r');

if (fgets($fp, 4) !== "\xef\xbb\xbf") {
    rewind($fp);
}

// call fgetcsv() as usual

【讨论】:

    猜你喜欢
    • 2021-05-23
    • 2015-09-22
    • 2021-08-05
    • 2021-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-20
    相关资源
    最近更新 更多