How to create single JSON for all matching results?

时间:2019-01-07 13:55:40

标签: php

I am fetching data from the database, and while I'm fetching, I check for each result if it matches certain criteria, if it does, I want it to add the row with all the details as a new object inside the same JSON, so that I end up with a single JSON that holds all the matching rows

while ($result = $stmt->fetch(PDO::FETCH_ASSOC)) {
    if (matching criteria){
        //add row to the JSON
    }
}

Right now I can add each row and echo it, but it overwrites the previous row:

while ($result = $stmt->fetch(PDO::FETCH_ASSOC)) {        
    if (matching criteria){
         $firstColumn = $result['firstColumn'];
         $secondColumn= $result['secondColumn'];
         //more columns if necessary. . .
         $myObj->firstColumn = $firstColumn ;
         $myObj->secondColumn= $secondColumn;       
         $myJSON = json_encode($myObj);
         echo $myJSON;
    }
}

2 个答案:

答案 0 :(得分:0)

you can use PDO::fetch_object for ever row and add them to assoc array/another object and then use the json_encode on it.

something like (pseudocode not tested) it will create json array with object for every row:

$out = [];
while($result = $stmt->fetch(PDO::FETCH_OBJ)
{
    if(matching){
        $out[] = $result;
    }
}
echo json_encode($out);

答案 1 :(得分:0)

尝试这种方式,使用myObj Data创建一个为该数组分配值的数组,并在获取数组集合后将其转换为Json对象

$data = array(array());
$i = 0;
$j = 0;
while ($result = $stmt->fetch(PDO::FETCH_ASSOC)) {        
    if (matching criteria){
         $firstColumn = $result['firstColumn'];
         $secondColumn= $result['secondColumn'];
         //more columns if necessary. . .
         $myObj->firstColumn = $firstColumn ;
         $myObj->secondColumn= $secondColumn;       
         $data[i][j]=$firstColumn;
         $j++;
         $data[i][j]=$secondCoulmn;
         $i++;
         $j--;
    }
}
$myJSON = json_encode($data);
echo $myJSON;