簡體   English   中英

PHP格式不正確的JSON

[英]malformed JSON with PHP

我是一個具有相當豐富經驗的.NET專家,但是最近進入了一個PHP項目,因此需要一些幫助。 我有這個PHP代碼,它准備一個最終的歌曲對象,然后用json_encode()對其進行JSON化,但是我很奇怪,我看到在JSON字符串的末尾添加了一些額外的null值,我似乎不明白為什么會這樣。

這是我的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

請幫助我了解我在這里做錯了什么?

錯誤。 json_encode不會在結尾處創建該null,而在此代碼之后,則會創建其他內容。 向我們展示其余的代碼,我們也許可以發現正在編寫的代碼。

全體朋友,我很抱歉,我之前應該已經將此作為答案,但問題不在於JSON。 它與fetchAll()一起使用。 感謝您的分析和幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM