使用PHP格式错误的JSON

时间:2015-11-27 03:48:14

标签: php json

我是一个有着相当长期经验的.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

请帮助我理解我在这里做错了什么?

2 个答案:

答案 0 :(得分:1)

错误。在这段代码之后,json_encode不会在最后创建那个null。向我们展示其余的代码,我们也许能够发现它是什么。

答案 1 :(得分:-1)

所有朋友,我道歉,因为我之前应该做出这个答案,但问题不在于JSON。它是使用fetchAll()。感谢分析和帮助我。