php - 如何在 PHP 中从 mysql 表创建嵌套 json
问题描述
**我在 mysql 中创建了两个表第一个表是 cat_names,id,第二个表是 Qoutes,id iam 从 php 脚本中检索,但我想嵌套
我被执行的时候是这样的**
[{"cat_names":"Animal","Qoutes":"this is id 1st text"},{"cat_names":"Animal","Qoutes":"this is 1st id text"},{"cat_names":"ball","Qoutes":"this is 2nd id text"},{"cat_names":"ball","Qoutes":"this is 2nd id text"},{"cat_names":"cat","Qoutes":"this is 3rd id text"},{"cat_names":"cat","Qoutes":"this is 3rd id text"}]
代码 :
$host = 'localhost';
$user = 'root';
$pwd = 'root';
$db = 'demoqouteapp';
$conn = mysqli_connect( $host,$user,$pwd,$db);
if( !$conn ) {
die ("Error in connection:" . mysqli_connect_error());
}
$response = array();
$sql_query = "select c.cat_names, q.Qoutes from categories AS c inner join `qoute` as q on c.id = q.id";
$result = mysqli_query( $conn, $sql_query );
if(mysqli_num_rows($result)> 0) {
while($row = mysqli_fetch_assoc($result)) {
array_push($response,$row);
}
} else {
$response['success'] = 0;
$response['message'] = 'No data';
}
echo json_encode($response);
mysqli_close($conn);
我想要一个数组中的 cat_names 并且引号也在类似数组中
[{
"cat_names": "animals",
"qoutes": [{
"qoutes": "this is 1 st qoute"
},
{
"qoutes": "this is 1 st qoute"
}]
}]
解决方案
您想在这里将多条记录中的数据分组到一个对象中 - 这是您需要自己做的事情。
这是最简单的,如果您首先使用类别作为关联数组键:
while($row = mysqli_fetch_assoc($result)) {
if(!isset($response[$row['cat_names']])) {
$response[$row['cat_names']] = [
'cat_names' => $row['cat_names'],
'qoutes' => []
];
}
$response[$row['cat_names']]['qoutes'][] = ['qoutes' => $row['Qoutes']];
}
如果$response[$row['cat_names']]
尚未设置,则意味着我们正在处理具有特定猫名的第一条记录。在这种情况下,我们初始化$response[$row['cat_names']]
为一个新数组,并cat_names
在其中设置,然后初始化qoutes
为一个空子数组。
在那之后,当前的引用(我假设你实际上的意思是你在这里有引用,所以现在可以修复拼写,在这之前会遇到麻烦......)被推入qoutes
子数组。
现在我们只需要再次摆脱外部级别的关联索引 - 否则,将其编码为 JSON 会给你一个对象,而不是一个数组。这可以使用 轻松完成array_values
,因此在循环之后放置:
$response = array_values($response);
echo json_encode($response);
......你应该有你想要的。
推荐阅读
- npm - Azure DevOps 管道中的 npm 版本
- scrapy - scrapy 为什么在调用提取时将 jsessionid 附加到 url?
- c# - 从 valuechanged 退订不起作用
- node.js - 通过 nextPageToken 在 google drive API 中检索下一页的正确语法是什么
- html - 如何根据屏幕大小拆分布局?(HTML/CSS)
- c# - 如何添加多个热键?像 f1 f2 f3
- android - 从 Play 商店安装时获取 java.lang.NullPointerException,但在本地工作正常
- android - 如何在 Kotlin 中使用 Single Live Event 显示 toast
- laravel - 我可以将 LaravelCollective/html 用于 Laravel 8 应用程序吗?
- html - 如何在可滚动的页面底部显示页脚?