繁体   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