【问题标题】:Strange issue with reading value from associative array in PHP 7.1 [duplicate]从 PHP 7.1 中的关联数组读取值的奇怪问题 [重复]
【发布时间】:2018-08-18 04:01:56
【问题描述】:

我发现基本脚本中的一些(应该很简单)PHP 代码存在一个奇怪的问题。

我有一个多维关联数组 $accounts,在使用 var_dump 时看起来像这样:

    Array(4) {
      [0] =>
      array(3) {
        'account' =>
        string(37) "Flood Cleanup City - Desktop - Exact "
        'parameter' =>
        string(23) "flood_cleanup_city_d_em"
        'phone' =>
        string(0) ""
      }
      [1] =>
      array(3) {
        'account' =>
        string(51) "Flood Cleanup City - Desktop - Exact Call Extension"
        'parameter' =>
        string(3) "N/A"
        'phone' =>
        string(0) ""
      }
      [2] =>
      array(3) {
        'account' =>
        string(38) "Flood Cleanup City - Desktop - Phrase "
        'parameter' =>
        string(23) "flood_cleanup_city_d_pm"
        'phone' =>
        string(0) ""
      }
      [3] =>
      array(3) {
        'account' =>
        string(52) "Flood Cleanup City - Desktop - Phrase Call Extension"
        'parameter' =>
        string(3) "N/A"
        'phone' =>
        string(0) ""}
}

所以,很简单。该数组在函数中生成并作为返回值传递给变量 $listAccounts。

我只想遍历 $listAccounts 并提取“帐户”值,所以我写了这个:

foreach($listAccount as $account)
{
    $accountName = $account['account'];
    echo $accountName;
}

我希望它会输出四个帐户字符串。相反,$account['account'] 返回 NULL。但是,如果我使用 array_keys 函数从数组中提取键的名称并使用此代码,它可以正常工作:

$accountName = $account[array_keys($account)[0]];

如果可能相关,生成多维数组的函数正在使用 fgetcsv() 函数来解析 CSV 文件:

function getAccounts()
{
    $handle = fopen("water.csv","r");
    $header = NULL;
    $accounts = array();
    $n = 0;
    while (!feof($handle)) {
        $account = fgetcsv($handle);
        if(!$header)
        {
            $header = $account;
        }
        else
        {
            $accounts[] = array_combine($header,$account);
        }
    }
    fclose($handle);
    echo var_dump($accounts);
    return $accounts;
}

【问题讨论】:

  • 您可能认为欺骗链接不相关,但它也直接相关,因为它也被忽略了。您在该文件中有一个 BOM,正在使用fgetcsv 中的第一个标题字段读取它。在进行 csv 解析之前,您需要摆脱它。

标签: php arrays csv


【解决方案1】:

“帐户”键名中有一个奇怪的第一个不可见符号。请在解析CSV文件后过滤数据。

【讨论】:

  • 该字符的十六进制代码是:efbbbf ... 这是 BOM(字节顺序标记)。如果可能的话,最好在没有它的情况下保存 .csv。但是如果你不能,那么在解析之前把它从文件的前面拉下来(因为修剪不会轻易摆脱)。
  • 谢谢你们!就是这样。我正在使用 PhpStorm,并且能够直接从 IDE 内部使用 CSV 文件上的“删除 BOM”选项。谢谢!
猜你喜欢
  • 2016-01-10
  • 2022-01-18
  • 2018-06-29
  • 2015-06-25
  • 1970-01-01
  • 2018-11-11
  • 1970-01-01
  • 2010-10-07
  • 2021-12-31
相关资源
最近更新 更多