如何从mysqli结果中构建正确的json? [英] How can I build a correct json from mysqli result?

查看:89
本文介绍了如何从mysqli结果中构建正确的json?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从myqli结果中构建一个json对象。我该怎么做呢目前它不会创建一个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.

这是我的代码:

$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"},....


推荐答案

不要为你将在

而不是:

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

do

$data[] = array("id"=>$id, "artist"=>$artist, "count"=>$count);

这篇关于如何从mysqli结果中构建正确的json?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆