**我已经在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"
}]
}]
答案 0 :(得分:0)
您要在此处将来自多个记录的数据分组为一个对象-这是您需要自己做的事情。
这是最简单的,如果先使用类别作为关联数组键:
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
初始化为空子数组。
此后,当前引号(我想您实际上是说您在这里有 quotes ,所以也许现在就解决拼写问题,然后再麻烦……)被推入{{1 }}子数组。
现在,我们只需要再次除去外部级别的关联索引-否则,将其编码为JSON将为您提供一个对象,而不是数组。使用qoutes
可以轻松完成此操作,因此在循环之后,您需要放置:
array_values
...,您应该拥有想要的东西。