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条)

报告相同问题?