【问题标题】:PHP Array_combine undefined indexPHP Array_combine 未定义索引
【发布时间】:2014-11-10 17:02:36
【问题描述】:

我想组合两个数组,一个作为键,另一个作为数据。 但是,当我print_r数组时,我看到键中添加了一个神秘的空间。即使我采用完全不同的数组,array_combine 之后的空格似乎也会重新出现。

此外,如果我尝试通过在键中添加空格来访问数组元素,我仍然会收到错误 Undefined offset: 200

这是我的代码:

$codes = file('H_codes.txt');
$sentences = file('H_sentences.txt');
$H_sentences_combined = array_combine($codes,$sentences);

echo $H_sentences_combined['200'];

我从两个文本文件中检索数组: H_codes.txt

200
201
202
...

$H_sentences 文件格式相同(即没有内联空格,只有下一行空格)

"Zeer licht ontvlambare aerosol."
"Ontvlambare aerosol."
"Zeer licht ontvlambare vloeistof en damp."
...

这是print_r($H_sentences_combined)的结果

 Array ( [200 ] => "Instabiele ontplofbare stof." [201 ] => "Ontplofbare stof: gevaar voor massa-explosie." [202 ] => "Ontplofbare stof, ernstig gevaar voor scherfwerking." ...)

我真的不知道出了什么问题。

感谢任何帮助! 谢谢。

【问题讨论】:

  • 读取的文件中的结束行字符可能存在问题。确保文件具有适合运行代码的操作系统的结束行字符。如果您在 windows 中创建文件并在 linux 或 mac 上读取它,则可能会产生这种效果。
  • 谢谢,好像是这样,但是如何通过 PHP 删除这些空格?
  • 只需使用 trim() php.net/manual/en/function.trim.php 或更好,但请查看 buggabill 的答案。他有更好的选择。

标签: php arrays indexing offset undefined-index


【解决方案1】:

那个多余的字符是换行符。 file 将这些添加到它读入数组的每一行中。

像这样改变你的文件调用来摆脱那些额外的换行符:

$codes = file('H_codes.txt', FILE_IGNORE_NEW_LINES);
$sentences = file('H_sentences.txt', FILE_IGNORE_NEW_LINES);
$H_sentences_combined = array_combine($codes,$sentences);

【讨论】:

    【解决方案2】:

    索引后面的字符实际上不是一个空格,它是一个换行符(或两个)。基本上,在您的文本文件中,每行末尾将是 \n 或 \r\n。要在插入之前删除这些,只需使用 PHP 内置的 trim($content) 函数,它将删除字符串左右两侧的所有空格。例如trim(' hello world! ') 将返回 'hello world!'

    【讨论】:

      猜你喜欢
      • 2013-01-26
      • 1970-01-01
      • 2015-03-24
      • 2018-01-25
      • 1970-01-01
      • 1970-01-01
      • 2014-07-29
      • 2015-01-20
      • 2014-12-19
      相关资源
      最近更新 更多