【问题标题】:How to group Objects in an Array using PHP PDO and MySQL?如何使用 PHP PDO 和 MySQL 对数组中的对象进行分组?
【发布时间】:2023-04-09 07:01:01
【问题描述】:

我有这个分类表

Category
============
id    name    ref_id
1     cat1    0
2     cat2    0
3     subCat1 1
4     subCat2 1
5     subCat3 2
6     subCat4 2

我想要一个看起来像这样的结果:

{items: [
    {catId: 1, subCat:[{name: subCat1}, {name:subCat2}]},
    {catId: 2, subCat:[{name: subCat2}, {name:subCat4}]}
]}

我试图通过以下方式解决这个问题:

$db = new PDO('mysql:host=localhost;dbname=test;charset=UTF-8', '', '');

$categories = $db -> query('SELECT * FROM category');

$results = array('items' => array());

foreach($categories as $row) {
    $subCategories = array();
    $results['items'][] = array('id' => $row['video_id'], 'subCat' => $subCategories);
}

echo json_encode($results);

在这种情况下,我不知道如何处理子类别。或者我做了什么来修复 $categories 的查询?有什么建议?谢谢。

【问题讨论】:

标签: php mysql pdo logic


【解决方案1】:

获取根类别,您需要将where ref_id=0 添加到您的查询中。然后在您的foreach 循环中,您需要再次查询以获取当前行的子类别(在第二个查询中使用"where ref_id=".$row['id'])。您使用另一个 foreach 循环编译 $subCategories 数组。哦,我将您代码中的'id' => $row['video_id'] 替换为'catId' => $row['id'] 以获得您需要的结果。

如下:

<?php
$db = new PDO('mysql:host=localhost;dbname=test', '', '');

$categories = $db->query('SELECT * FROM category where ref_id=0');

$results = array('items' => array());

foreach($categories as $row) {
  $subCategories = array();

  $sCategories = $db->query('SELECT * FROM category where ref_id='.$row['id']);
  foreach($sCategories as $subCat){
    $subCategories[] = array('name'=>$subCat['name']);
  }

  $results['items'][] = array('catId' => $row['id'], 'subCat' => $subCategories);
}

echo json_encode($results);

我已经在我这边重新创建了你的数据库,当我运行它时,我得到了

{"items":[
   {"catId":"1","subCat":[{"name":"subcat1"},{"name":"subcat2"}]},
   {"catId":"2","subCat":[{"name":"subcat3"},{"name":"subcat4"}]}
]}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-20
    • 2021-03-30
    • 2016-11-07
    • 2015-10-19
    相关资源
    最近更新 更多