[英]Creating JSON table from SQL query
I want to create a JSON table from the results of a SQL query. 我想根据SQL查询的结果创建JSON表。 I tried the query on phpMyAdmin and it is correct (I get the data that I want) but then when I try to convert it to a JSON table using the code below, the result is a table with the correct structure but non of the values.
我在phpMyAdmin上尝试了查询,它是正确的(我得到了我想要的数据),但是当我尝试使用下面的代码将其转换为JSON表时,结果是具有正确结构但没有值的表。
/* select all moches from the table moches */
$query="SELECT municipio, SUM(moche) AS moche FROM moches GROUP BY municipio";
$result = $mysqli->query($query);
$rows = array();
$table = array();
$table['cols'] = array(
array('label' => 'Municipio', 'type' => 'string'),
array('label' => 'Cantidad total en moches', 'type' => 'number')
);
foreach($result as $r) {
$temp = array();
//Create the different states
$temp[ ] = array('v' => (string) $r['municipio']);
// Total de moches
$temp[ ] = array('v' => (int) $r['moche']);
$rows[ ] = array('c' => $temp);
}
$table['rows'] = $rows;
// convert data into JSON format
$jsonTable = json_encode($table);
phpMyAdmin允许以JSON格式导出,也许可以为您提供帮助。
nitpick: there's no such thing as a "json table". nitpick:没有“ json表”之类的东西。 There's JSON strings, which are plaintext strings that represent a data structure in some other language, eg javascript.
有JSON字符串,它们是纯文本字符串,以其他语言(例如javascript)表示数据结构。
Your problem is that you're trying to loop over a mysqli result handle. 您的问题是您试图遍历mysqli结果句柄。 That's generally a single ROW of data, not the entire result set.
通常,这是单个ROW数据,而不是整个结果集。
You should have something more like: 您应该有更多类似的东西:
$result = $mysqli->query($sql);
$temp = array();
while($row = $result->fetch_row()) {
$temp[] = $row;
}
echo json_encode($temp);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.