【发布时间】: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