php - 使用php和mysql在Json脚本中生成嵌套的同结构表

标签 php mysql json postgresql

我的 json 和 php 问题:如何生成类似下面部分的 json 脚本表的内容,其中包含嵌套在其中的具有相同结构的另一个表?我想使用 mysql 从 php 代码生成它。我也在网上搜索过,但没有找到任何解决方案。我刚刚在 postgre 数据库中通过使用 mysql 中尚不支持的“WITH”子句在 this link 中发现了这样的情况|

{
  "categories": [
    {
      "id": 1,
      "name": "Electronic",
      "children": [
        {
          "id": 11,
          "name": "Computer",
          "children": [
            {
              "id": 111,
              "name": "Desktop",
              "children": []
            },
            {
              "id": 112,
              "name": "Labtop",
              "children": []
            }
          ]
        },
        {
          "id": 12,
          "name": "Mobile",
          "children": [
            {
              "id": 121,
              "name": "Phone",
              "children": []
            },
            {
              "id": 122,
              "name": "Tablet",
              "children": []
            }
          ]
        }
      ]
    }
  ]
}

最佳答案

如果我没理解错的话,你要做的是将数组结果从 SQL 转换为 JSON 形式的树状结构

假设您的目标对象结构如下所示:

[
   "id"=>10,
   "name"=>"Computer",
   "children"=[]
]

SQL 的结果数组在 php 中应该是这样的:

[
   "id"=>12,
   "name"=>"Laptop",
   "parentId"=>10
]

然后您可以尝试编写一些 php 函数(或存储库方法)来为您完成这项工作。

<?php
function arrayRemove(&$array,&$object){
    if (($key = array_search($object, $array)) !== false) {
    unset($array[$key]);
    }
}
function findRoots(&$array,$baseRoot){
    $roots=[];
    foreach($array as &$element)
    {
        $cpy=null;
        if(
            ($baseRoot==null&&$element['parentId']==null)||
            ($baseRoot!==null&&$element['parentId']==$baseRoot['id'])
        ){
            $cpy=$element;
            arrayRemove($array,$element);
            array_push($roots,[
                'id'=>$cpy["id"],
                'name'=>$cpy["name"],
                'children'=>findRoots($array,$cpy)
                ]);
        }
    }
    return $roots;
}
function foo($array){
    $object=["categories"=>[]];
    $roots=findRoots($array,null);
    $object["categories"]=$roots;
    return json_encode($object);
}
echo foo([
    ['id'=>1,'name'=>'A','parentId'=>null],
    ['id'=>2,'name'=>'bb','parentId'=>1],
    ['id'=>3,'name'=>'ccc','parentId'=>2],
    ['id'=>4,'name'=>'DDDD','parentId'=>1]
    ]);
?>

上面代码的结果应该是这样的:

{
    "categories":[
        {
            "id":1,
            "name":"A",
            "children":[
                {
                    "id":2,
                    "name":"bb",
                    "children":[
                        {
                            "id":3,
                            "name":"ccc",
                            "children":[]
                        }
                    ]
                },
                {
                     "id":4,
                     "name":"DDDD",
                     "children":[]
                }
            ]
        }
    ]
}

作为Diogo Sgrillo提到过,然后您可以在数据库中创建一个包含 id、name 和 parentId 字段的表。假设 id 和 parentId 是 int(11),name 是 varchar(255),parentId 是 categories:id 的外键。 phpMyAdmin 为表生成了以下 SQL:

CREATE TABLE `categories` (
  `id` int(11) NOT NULL,
  `name` varchar(255) COLLATE utf8_bin NOT NULL,
  `parentId` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
ALTER TABLE `categories`
  ADD PRIMARY KEY (`id`),
  ADD KEY `parentId` (`parentId`);
ALTER TABLE `categories`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
ALTER TABLE `categories`
  ADD CONSTRAINT `parent_fk` FOREIGN KEY (`parentId`) REFERENCES `categories` (`id`) ON DELETE SET NULL ON UPDATE CASCADE;

如果你想反转这个过程,只需编写一个函数,获取 parentId 和父子的数组:

function reversedProcess(&$children,$parentId)
{
    $array=[];
    foreach($children as $child)
    {
        array_push($array,['id'=>$child['id'],'name'=>$child['name'],'parentId'=>$parentId]);
        $array=array_merge($array,reversedProcess($child['children'],$child['id']));
    }
    return $array;
}

关于php - 使用php和mysql在Json脚本中生成嵌套的同结构表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41366486/

相关文章:

java - JSONException : Value <br of type java. lang.String 无法转换为 JSONObject

javascript - 未捕获的语法错误 : Unexpected token < on line 1

javascript - AngularJS ng-重复 : show data only when data is not false

php - 连接三个表时,MySQL 不返回任何内容。两个表在第三个表中有外键。怎么了?

php - Codeigniter 3.0 查询错误

javascript - 在 PHP 中转义 json 数据而不使用 JS 注释 hack 的正确方法

mysql - Sequel Pro(MySQL)执行联接查询(6000 * 5,000,000)

mysql - React Native 获取 MYSQL 中的数据

php - 如何在 Laravel 5.8 中使用 IF 和 ELSE 检查 mysql 表 NULL 或 NOT?

php - 如何在 Laravel 中的 Input::all() 之后附加额外的值