【php】implodeしたら「Notice: Array to string conversion」が出た
implodeとは
implode — 配列要素を文字列により連結する
です。
Notice: Array to string conversionとは
ようするに、配列を文字列に変換しようとしている。ということです。
「Notice: Array to string conversion」の原因と解決
「Notice: Array to string conversion」の原因
implodeの引数に使っていた配列の中身に空の配列が混ざっていた
XMLをパースしていたのですが、その中に空のものがあったようです。
<array>
<word>aaaa</word>
<word>bbbb</word>
<word>cccc</word>
<word>dddd</word>
<word>eeee</word>
<word>ffff</word>
<word></word>
<word>gggg</word>
</array>
これをvar_dumpすると
array(7) {
[0] =>
string(4) "aaaa"
[1] =>
string(4) "bbbb"
[2] =>
string(4) "cccc"
[3] =>
string(4) "dddd"
[4] =>
string(4) "eeee"
[5] =>
string(4) "ffff"
[6] =>
array(0) {}
[7] =>
}
となり、6番目の配列がおかしくてエラーがでます。
「Notice: Array to string conversion」の解決
チェック処理を入れました。
$result = '';
$word_list = array();
foreach ( $array as $key => $word ) {
//空ではないかつ、配列でない場合のみ追加
if ( isset( $word ) && !is_array( $word ) ){
$word_list = array_push($word_list, $word);
}
}
$result = implode( ',', $word_list );
勉強になりました!!