我是一個有相當長的經驗,但最近拉入PHP項目的.NET人,所以需要一些幫助。我有這個PHP代碼準備了一個最終的歌曲對象,然後用json_encode()
對它進行JSON化,但是我蠻橫地看到一些額外的值null
添加在JSON字符串的末尾,我似乎不明白爲什麼會這樣。格式錯誤的JSON與PHP
這是我的PHP代碼
foreach($result as $item) {
++$index;
$hymn->id=$item['id'];
$hymn->refrain=$item['refrain'];
if ($index == 1) { $hymn->stanza1=$item['stanzaText']; }
if ($index == 2) { $hymn->stanza2=$item['stanzaText']; }
if ($index == 3) { $hymn->stanza3=$item['stanzaText']; }
if ($index == 4) { $hymn->stanza4=$item['stanzaText']; }
if ($index == 5) { $hymn->stanza5=$item['stanzaText']; }
if ($index == 6) { $hymn->stanza6=$item['stanzaText']; }
if ($index == 7) { $hymn->stanza7=$item['stanzaText']; }
if ($index == 8) { $hymn->stanza8=$item['stanzaText']; }
if ($index == 9) { $hymn->stanza9=$item['stanzaText']; }
if ($index == 10) { $hymn->stanza10=$item['stanzaText']; }
}
json_encode($hymn);
以上代碼生成額外null
一個JSON結束大括號後,如下圖所示。
{
"id":"1",
"refrain" : "Jesus, Jesus, how I trust Him!\nHow I\u2019ve proved Him o\u2019er and o\u2019er;\nJesus, Jesus, precious Jesus!\nOh, for grace to trust Him more!",
"stanza1" : "Tis so sweet to trust in Jesus,\nJust to take Him at His Word;\nJust to rest upon His promise,\nAnd to know, \u201cThus saith the Lord!\u201d",
"stanza2" : "Oh, how sweet to trust in Jesus,\nJust to trust His cleansing blood;\nAnd in simple faith to plunge me\n\u2019Neath the healing, cleansing flood!",
"stanza3" : "Yes, \u2019tis sweet to trust in Jesus,\nJust from sin and self to cease;\nJust from Jesus simply taking\nLife and rest, and joy and peace.",
"stanza4" : "I\u2019m so glad I learned to trust Thee,\nPrecious Jesus, Savior, Friend;\nAnd I know that Thou art with me,\nWilt be with me to the end"
}null
請幫助我瞭解我在這裏做什麼錯?
檢查這個http://stackoverflow.com/questions/3180690/php-json-encode-returning-null – codenut
'@ codenut'我相信我的問題是不同的,那麼你在提到的線程中的問題。我的所有JSON元素與花括號中的預期完全相同。但在結束大括號後,它只是增加了額外的'null'。只是不明白從哪裏來。 –
你可以在這裏發佈輸入嗎? – codenut