使用PHP将数组转换/查询为JSON

I have a SELECT query that results in something like this:

USER_ID: 000030 USERNAME: Oprah RATING: 5
USER_ID: 000033 USERNAME: Pitbull RATING: 8

What I need is to display it in this form:

[[{"USER_ID":"000030","USERNAME":"Oprah","RATING":"5"},{"USER_ID":"000033","USERNAME":"Pitbull","RATING":"8"}]]

Generally I get this desired result with this SELECT:

try {
  $stmt = $conn->prepare("SELECT USER_ID, USERNAME, RATING FROM table");
  $stmt -> execute(array($userid));
  while($row = $stmt->fetchAll(PDO::FETCH_ASSOC)) {
    $output[] = $row;
  }
}
print(json_encode($output));

But this time I had to get the result in this form:

try {
  $stmt = $conn->prepare("SELECT USER_ID, USERNAME, RATING FROM table");        
  $stmt -> execute(array($userid));
  while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    //$output[] = $row;
    $row2[$i][$j] = $row['USER_ID'];
    $j++;
    $row2[$i][$j] = $row['USERNAME'];
    $j++;       
    $row2[$i][$j] = $row['RATING'];
    $i++;
    $j=0;               
  }
}

How can I convert it into the desired form or form the query to produce it?

I tried these:

print(json_encode($row2));
[["000030","Oprah","5"],["000033","Pitbull","8"]]

$output[] = $row2;
print(json_encode($output));
[[["000030","Oprah","5"],["000033","Pitbull","8"]]]

For json_encode() to produce a json string that includes the associative indices, they need to be in the array you are encoding. If the indices are 0, 1, 2, etc., the indices will not show up in the json string.

Try this:

$i=0;
while(...) {
    $row2[$i]['USER_ID'] = $row['USER_ID'];
    $row2[$i]['USERNAME'] = $row['USERNAME'];      
    $row2[$i]['RATING'] = $row['RATING'];
    $i++;
}
...
print_r(json_encode($row2));

Consider this PHP snippet for clarification.


Alternative methods of building array:

while(...) {
    $row2[] = array(
        'USER_ID' = $row['USER_ID'],
        'USERNAME' = $row['USERNAME'],
        'RATING' = $row['RATING']
    );
}

// OR

$i=0;
while(...) {
    foreach ($row as $key => $val) {
        $row2[$i][$key] = $val;
    }
    $i++;
}
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    $output[] = array("USER_ID" => $row["USER_ID"], 
                     "USERNAME" => $row["USERNAME"], 
                       "RATING" => $row["RATING"],
                     );
}
print(json_encode($output));