英文:
Create json array from multiple sql table
问题
这是你期望的 JSON 结果:
{"table":[
{
"table_id": "1",
"table_name": "Table 1",
"price": [
"20.00","15.00","7.90"
]
},
{
"table_id": "2",
"table_name": "Table 2",
"price": [
"7.90","15.00"
]
}
]}
英文:
I have create the json file from the sql table but the output is not same with the output i expected. Below is my code to create the json file from the sql table
<?php
include 'config.php';
$sql = "SELECT table_id, table_name,GROUP_CONCAT(price) price FROM tables INNER JOIN table_orders ON table_id = res_table_id GROUP BY table_id";
$result = mysqli_query($mysqli,$sql);
while($data1 = $result->fetch_assoc()){
$data[] = $data1;
}
$encoded_data = json_encode($data,JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
file_put_contents('data_json',$encoded_data);
?>
The output will look like this
[
{
"table_id": "1",
"table_name": "Table 1",
"price": "20.00,15.00,7.90"
},
{
"table_id": "2",
"table_name": "Table 2",
"price": "7.90,15.00"
}
]
I want my result something like the output below:
{"table":[
{
"table_id": "1",
"table_name": "Table 1",
"price": [
"20.00","15.00","7.90"
]
},
{
"table_id": "2",
"table_name": "Table 2",
"price": [
"7.90","15.00"
]
}
]}
答案1
得分: 0
<?php
include 'config.php';
$sql = "SELECT table_id, table_name, GROUP_CONCAT(price) price FROM tables INNER JOIN table_orders ON table_id = res_table_id GROUP BY table_id";
$result = mysqli_query($mysqli, $sql);
$data = [];
while ($data1 = $result->fetch_assoc()) {
$data1['price'] = explode(',', $data1['price']);
$data[] = $data1;
}
$encoded_data = json_encode(['table' => $data], JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
file_put_contents('data_json', $encoded_data);
这段代码的功能:
在初始循环中,首先按照你的要求格式化数组项。然后,通过传入你喜欢的嵌套结构来格式化JSON字符串。
有一些优化的方法,但这就是它的要点。
<details>
<summary>英文:</summary>
<?php
include 'config.php';
$sql = "SELECT table_id, table_name,GROUP_CONCAT(price) price FROM tables INNER JOIN table_orders ON table_id = res_table_id GROUP BY table_id";
$result = mysqli_query($mysqli,$sql);
$data = [];
while($data1 = $result->fetch_assoc()){
$data1['price'] = explode(',', $data1['price']);
$data[] = $data1;
}
$encoded_data = json_encode(['table' => $data], JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
file_put_contents('data_json', $encoded_data);
What this does:
In your initial loop, you first format your array items in the way you want. Then you can format your JSON string in the nested structure you want by passing in the format you like.
There are a few ways to optimize this, but that's the gist of it.
</details>
# 答案2
**得分**: -1
$my_new_data = [];
while ($data1 = $result->fetch_assoc()) {
array_push($my_new_data, $data1);
}
<details>
<summary>英文:</summary>
$my_new_data = [];
while($data1 = $result->fetch_assoc()){
array_push($my_new_data, $data1);
}
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论