이 데이터베이스 구조가 있습니다.
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
. 데이터 계층 구조를 포함합니다.
도움이되기를 바랍니다.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다