如何在php中生成格式正确的json?

我试图用我的数据库的数据生成一个 json,所以当我收到数据时一切都很好,当我将数据以 JSON 格式放置时就会出现问题,看起来这是错误的:


{"comment":[{"id_comment":1,"photo":"imgU\/default.png","full_name":"MercadoPago","comment":"Primero"}]}{"comment":[{"id_comment":2,"photo":"imgU\/default.png","full_name":"MercadoPago","comment":"Segundo"}]}

所以我想生成一个看起来像这样的json:


[{"id_comment":1,"photo":"imgU\/default.png","full_name":"MercadoPago","comment":"Primero"},

{"id_comment":2,"photo":"imgU\/default.png","full_name":"MercadoPago","comment":"Segundo"}]

我的代码是下一个:


global $id_comentador;

global $id_comentario;

global $comment;


$arregloComentarios = json_decode($row['comentarios'], true);


foreach ($arregloComentarios as $value) {


    $id_comentario = $value["id_comentario"];

    $id_comentador = $value["id"];

    $comment = $value["comment"];


    $consultarComentador = "select id,first_name,last_name,foto from users where id='$id_comentador';";


    $coo["comment"] = array();

    $arregloProyectos = traerDatos($consultarComentador);

    $num = count($arregloProyectos);


    if ($num > 0) {


        foreach ($arregloProyectos as $row2) {


            $foto = $row2["foto"];

            $foto2 = $row2["first_name"];

            $foto3 = $row2["last_name"];

            $tmp = array();

            $tmp["id_comment"] = $id_comentario;

            $tmp["photo"] = $foto;

            $tmp["full_name"] = $foto2.''.$foto3;

            $tmp["comment"] = $comment;

            global $coo;

            $coo['comments'] = array();

            array_push($coo["comments"], $tmp);


        }//Cierra foreach


        echo json_encode($coo);

    }

}

我将不胜感激您的回答。


芜湖不芜
浏览 83回答 1
1回答

万千封印

(复制自评论)$comments在顶部之外创建一个数组foreach并推入该数组而不是$coo["comments"]. 然后,echo json_encode($comments)在外面做之后foreach。global $id_comentador;global $id_comentario;global $comment;$arregloComentarios = json_decode($row['comentarios'], true);$comments = [];foreach ($arregloComentarios as $value) {    $id_comentario = $value["id_comentario"];    $id_comentador = $value["id"];    $comment = $value["comment"];    $consultarComentador = "select id,first_name,last_name,foto from users where id='$id_comentador';";    $arregloProyectos = traerDatos($consultarComentador);    $num = count($arregloProyectos);    if ($num > 0) {        foreach ($arregloProyectos as $row2) {            $foto = $row2["foto"];            $foto2 = $row2["first_name"];            $foto3 = $row2["last_name"];            $tmp = array();            $tmp["id_comment"] = $id_comentario;            $tmp["photo"] = $foto;            $tmp["full_name"] = $foto2.''.$foto3;            $tmp["comment"] = $comment;            $comments[] = $tmp;        }//Cierra foreach    }}echo json_encode($comments);
打开App,查看更多内容
随时随地看视频慕课网APP