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

时间:2014-07-15 20:32:04

标签: php json

我有一个SELECT查询,结果是这样的:

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

我需要的是以这种形式显示它:

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

通常我用这个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));

但是这次我必须以这种形式得到结果:

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;               
  }
}

如何将其转换为所需的格式或形成查询以生成它?

我试过这些:

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

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

2 个答案:

答案 0 :(得分:1)

要使json_encode()生成包含关联索引的json字符串,它们必须位于您正在编码的数组中。如果索引是0,1,2等,索引将不会显示在json字符串中。

试试这个:

$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));

考虑this PHP snippet进行澄清。


构建数组的替代方法:

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++;
}

答案 1 :(得分:0)

while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    $output[] = array("USER_ID" => $row["USER_ID"], 
                     "USERNAME" => $row["USERNAME"], 
                       "RATING" => $row["RATING"],
                     );
}
print(json_encode($output));