Json显示为单独格式

时间:2018-05-02 09:39:49

标签: php arrays json wordpress

我通过PHP代码成功获得Wordpress帖子评论。现在我想以JSON格式显示所有帖子评论。我提到了一些例子来完成这个进展,但所有评论(JSON格式)都是单独显示的。

参见样本结果:

[{
    "author": "JimmiXzSq",
    "comment": "test1"
}]

[{
    "author": "MoseJackswka",
    "comment": "test2"
}]

但我想显示正确的JSON格式

我的锻炼代码:

foreach ( $comments as $comment ) :

  $getauthor = $comment->comment_author ;
  $getcontent =  $comment->comment_content;
  $test1=  array('author' => $getauthor, 'comment' => $getcontent);

  $displaycomments = json_encode(array(($test1)),true);
  echo $displaycomments;
endforeach;

1 个答案:

答案 0 :(得分:0)

如果您想将所有评论插入一个json:

$comments = array();

foreach ( $comments as $comment ) :
    $getauthor = $comment->comment_author ;
    $getcontent =  $comment->comment_content;
    $tmp=  array('author' => $getauthor, 'comment' => $getcontent);

    $comment[] = $tmp;
endforeach;

$displaycomments = json_encode($comments);
echo $displaycomments ;

将给出

{
    {
        "author": "JimmiXzSq",
        "comment": "test1"
    }
    ,
    {
        "author": "MoseJackswka",
        "comment": "test2"
    }
}