drxv39706 2014-07-15 20:32
浏览 40
已采纳

使用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"]]]
  • 写回答

2条回答 默认 最新

  • dongwalun2507 2014-07-15 20:46
    关注

    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++;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制