我有这样的数据库结构:
USERS
-----------------------------
| id | parent | name | points
-----------------------------
我需要从此结构中获取多重嵌套(分层)数组。
例如,从这个数据:
USERS
------------------------------
| id | parent | name | points
------------------------------
| 1 | null | A | 20
| 2 | 1 | B | 10
| 3 | 1 | C | 30
| 4 | 3 | D | 40
| 5 | 2 | E | 50
------------------------------
如何获取以下 php 数组:
[
"1" => [
"points" => 20,
"childs" => [
"2" => [
"points" => 10,
"childs" => [
"5" => [
"points" => 50,
"childs" => null
]
]
],
"3" => [
"points" => 30,
"childs" => [
"4" => [
"points" => 40,
"childs" => null
]
]
]
]
]
]
谢谢!
最佳答案
这是一个无限深度的工作示例:
//Obtain this from database
$datas = [
[
"id" => 1,
"parent" => null,
"name" => "A",
"points" => 20
],
[
"id" => 2,
"parent" => 1,
"name" => "B",
"points" => 10
],
[
"id" => 3,
"parent" => 1,
"name" => "C",
"points" => 30
],
[
"id" => 4,
"parent" => 3,
"name" => "D",
"points" => 40
],
[
"id" => 5,
"parent" => 2,
"name" => "E",
"points" => 50
]
];
$ordered = [];
for($i=0; $i<count($datas); $i++)
{
$data = &$datas[$i];
$id = $data["id"];
$data["childs"] = [];
$ordered[$id] = &$data;
}
$result = [];
for($i=0; $i<count($datas); $i++)
{
$data = &$datas[$i];
$id = $data["id"];
$parent = $data["parent"];
//unset not needed properties
unset($data["id"]);
unset($data["parent"]);
if($parent){
$ordered[$parent]["childs"][$id] = &$data;
} else {
$result[$id] = &$data;
}
}
结果是:
print_r($result);
Array
(
[1] => Array
(
[name] => A
[points] => 20
[childs] => Array
(
[2] => Array
(
[name] => B
[points] => 10
[childs] => Array
(
[5] => Array
(
[name] => E
[points] => 50
[childs] => Array
(
)
)
)
)
[3] => Array
(
[name] => C
[points] => 30
[childs] => Array
(
[4] => Array
(
[name] => D
[points] => 40
[childs] => Array
(
)
)
)
)
)
)
)
ordered
包含一组按 id“排序”的数据(因此您可以轻松搜索项目)
result
包含数据层次结构。
希望对你有帮助
关于php - 获取mysql获取分层数据结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41291683/