我有以下MySQL表:
id desc qty
--------------------
10 abc 5
20 xyz 12
30 qwe 9
如何使用PHP / MySQL查询创建以下JSON文件?
{
"10":{"desc":"abc","qty":"5"},
"20":{"desc":"xyz","qty":"12"},
"30":{"desc":"qwe","qty":"9"}
}
这是我的尝试
$query="SELECT id,desc,qty FROM table";
$result = @mysql_query($query);
while ($row=mysql_fetch_object($result))
{
$data[]=$row;
}
echo json_encode($data);
结果是一个数组,我不知道如何正确显示它
[
{"id":"10","desc":"abc","qty":"5"},
{"id":"20","desc":"xyz","qty":"15"},
{"id":"30","desc":"qwe","qty":"9"}
]
感谢任何帮助
答案 0 :(得分:1)
有很多方法可以实现这一目标。其中一个是在下面。更改您的数据库凭据和表名。
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "myDB";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM TableName";
$result = $conn->query($sql);
$results_array =array();
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$results_array[$row['id']] = array(
'desc'=>$row['desc'],
'qty'=>$row['qty'],
);
}
} else {
echo "0 results";
}
$json_array = json_encode($results_array);
echo $json_array;
结果应该看起来很相似
{
"1":{"desc":"abc","qty":"12"},
"2":{"desc":"xyz","qty":"54"}
}
答案 1 :(得分:0)
感谢您修改问题。您可以使用另一个循环更改结果的结构:
foreach($data as $d)
$r[$d->id] = ['desc' => $d->desc, 'qty' => $d->qty];
$data = $r;
正上方:
echo json_encode($data);
或您可以调整while循环以获得相同的结果:
$data[$row->id] = ['desc' => $row->desc, 'qty' => $row->qty];
或你可以使用数组列(再次在json_encode上方):
$data = array_column($data, null, 'id');
最后一个示例会产生略微不同的输出,但您仍可以在许多情况下使用它。如果你不能选择前两个选项。