Json Отображается в индивидуальном формате - PullRequest
0 голосов
/ 02 мая 2018

Я успешно получаю комментарии к Wordpress через код PHP. Теперь я хочу отобразить все комментарии в формате 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 голосов
/ 02 мая 2018

Если вы хотите вставить все свои комментарии в один 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"
    }
}
...