dongxi5494 2014-11-10 17:02
浏览 26
已采纳

PHP Array_combine未定义索引

I want to combine two arrays, one as a key and the other as the data. However when I print_rthe array, I see that there was a mysterious space added to the keys. Even if I take a completely different array, the spaces seem to reappear after the array_combine.

Also if I try to access the array element by adding a space tot the key, I still get the error Undefined offset: 200.

This is my code:

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

echo $H_sentences_combined['200'];

I retrieve the arrays from two text files: H_codes.txt

200
201
202
...

and the $H_sentences file is in the same format (i.e. with no inline spaces, only next line spaces)

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

This is the result of the print_r($H_sentences_combined)

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

I really have no idea what's going wrong.

Any help is appreciated! Thank you.

  • 写回答

2条回答 默认 最新

  • drbhjey445647 2014-11-10 17:12
    关注

    That extra character is a newline character. file adds these to each line that it reads into an array.

    Change your file calls like so to get rid of those extra new line characters:

    $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);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器