drhs13583567608 2013-05-29 14:54
浏览 34
已采纳

如何从mysqli结果中构建正确的json?

I am trying to build a json object from my mysqli result. How do I go about it. At the moment it does not create a json looking object.

Here is my code:

$result = $dataConnection->prepare("SELECT id, artist, COUNT(artist) AS cnt FROM {$databasePrefix}users GROUP BY artist ORDER BY cnt DESC LIMIT 0 , 30");
$result->execute();
if($result->error)
{
die("That didn't work. I get this: " . $result->error);
}
$result->bind_result($id, $artist, $count);
$data = array();
while($result->fetch()){
$data[] = '{ id :'.$id.', artist :'.$artist.', count :'.$count.'}';
}
echo json_encode($data);
$dataConnection->close();

I want a data object like:

{"id":"27","artist":"myArtist","count":"29"},....
  • 写回答

4条回答 默认 最新

  • duanhuangyun3887 2013-05-29 14:57
    关注

    Don't build your json for the values array that you will call json_encode on

    instead of:

    $data[] = '{ id :'.$id.', artist :'.$artist.', count :'.$count.'}';
    

    do

    $data[] = array("id"=>$id, "artist"=>$artist, "count"=>$count);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题