多个JSON根元素-PHP

时间:2019-03-07 17:15:07

标签: php json

我正在创建一些对象的数组,例如下面的代码:

$eventos = DB::select('SELECT *
    FROM eventos
    ORDER BY timestamp DESC'); 
    foreach ($eventos as $evento){
        $produtos = DB::select("SELECT * 
        FROM produtos
        WHERE transaction_id = '$evento->transaction_id'"); 
        $eventos = array(
            'timestamp' => $evento->timestamp,
            'revenue' => $evento->revenue,
            'transaction_id' => $evento->transaction_id,
            'store_name' => $evento->store_name,
            'products' => array()
            ); 
            foreach ($produtos as $produto){ 
                $products[] = array(
                    'name' => $produto->nome,
                    'price' => $produto->preco,
                    );
            }
        $eventos['products'] = $products;
        echo json_encode($eventos);
    }
}

但是我的JSON无效:根据验证器,出现错误“多个JSON根元素”。应该是

]

},

{

不是

]

} {

我该如何实现?

 {
"timestamp":"2016 1", "revenue":120, "transaction_id":334, "store_name":"Uai", "products":[
{
"name":"Black Shoes", "price":99 } ] }{ //ERROR here "timestamp":"2016 2", "revenue":250, "transaction_id":6665, "store_name":"M Mall", "products":[
{
"name":"Blue Shirt", "price":100 }, {
"name":"Pink Pants", "price":150 } ] }

1 个答案:

答案 0 :(得分:3)

您不会回传一系列JSON文档,那是无效的。

相反,您需要组装一个最终单数数组,并将其编码为JSON:

$final = [ ];
$eventos = DB::select('SELECT *
    FROM eventos
    ORDER BY timestamp DESC'); 
    foreach ($eventos as $evento){
        $produtos = DB::select("SELECT * 
        FROM produtos
        WHERE transaction_id = '$evento->transaction_id'"); 
        $data = array(
            'timestamp' => $evento->timestamp,
            'revenue' => $evento->revenue,
            'transaction_id' => $evento->transaction_id,
            'store_name' => $evento->store_name,
            'products' => array()
            ); 
            foreach ($produtos as $produto){ 
                $products[] = array(
                    'name' => $produto->nome,
                    'price' => $produto->preco,
                    );
            }
        $data['products'] = $products;
        $final[] = $data;
    }
}

echo json_encode($final);

我不知道DB::Select是什么,但是如果它只是mysqli或PDO之类的脆弱包装,那么如果它不支持占位符值,就会出现问题。 请勿直接在查询中插入数据。而是使用?之类的占位符,并分别绑定值。

您的数据库驱动程序(无论它是什么)可能已经支持此功能,因此请立即进行检查以避免将来出现潜在的问题。