Looking for a better way to write code

suppose there are two tables

CREATE TABLE IF NOT EXISTS `structure` (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT "",
  `name` varchar(64) DEFAULT "" COMMENT "",
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT = "";

CREATE TABLE IF NOT EXISTS `structure` (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT "",
  `realname` varchar(64) DEFAULT ""  COMMENT "",
  `structure_id` int(11) DEFAULT NULL COMMENT "",
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT = "";

there is an one-to-many relationship between the department table and the personnel table. How to write the interface to generate this structure?

{
    data: [{
        "id": "", // ID
        "name": "", // 
        "list": [{ // 
            "id": "", // ID
            "realname" : "", // 
        }],
    }]
}

now I have a way to write it, but I don"t think it"s very good (using tp5 syntax), that is, I look up all the data and process it into an array.

function test()
{
    $structure = Db::name("structure")->select();
    $user = Db::name("user")->select();
    foreach ($structure as &value) {
        foreach ($user as $k => $v) {
            if ($value["id"] == $v["structure_id"]) {
                $value["list"][] = $v;
                unset($user[$k]);
            }
        }
    }
    
    return $structure;
}
Php
Mar.22,2021

your idea is wrong, it should be a related query.
sql:

select * from  left join  on id = id

the result set obtained in this way is the dataset with the department as the primary user, and finally ok the data combined into your format by traversing it.

MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1b40188-2bd3c.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1b40188-2bd3c.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?