首页 > 解决方案 > 如何在 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"
                    }]
 }]

标签: phpmysql

解决方案


您想在这里将多条记录中的数据分组到一个对象中 - 这是您需要自己做的事情。

这是最简单的,如果您首先使用类别作为关联数组键:

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);

......你应该有你想要的。


推荐阅读