質問編集履歴
2
修正内容の文言に不備あったため修正
title
CHANGED
File without changes
|
body
CHANGED
@@ -26,7 +26,7 @@
|
|
26
26
|
}
|
27
27
|
|
28
28
|
```
|
29
|
-
※$definitionListはDBから取得した
|
29
|
+
※$definitionListはDBから取得したArrayCollectionで内部に自身のIDと親データを持っています。
|
30
30
|
```
|
31
31
|
//ツリー構造を作る。
|
32
32
|
private function createNestRecursive(array $newList)
|
1
情報不足だったため、追記しました。ご迷惑をおかけしました。
title
CHANGED
File without changes
|
body
CHANGED
@@ -1,26 +1,53 @@
|
|
1
1
|
初心者質問で申し訳ございませんが、phpの参照渡しについて教えてください。
|
2
2
|
親子関係のあるデータをもとにツリー構造を作ろうと、いろいろ調べて以下のようなコードを書きました。
|
3
|
+
|
4
|
+
参考にしたのはこちらのQiita記事です。
|
5
|
+
[リンク内容](https://qiita.com/ibarakidouji/items/52c0b41e10e8d9a981b9)
|
3
6
|
たしかに参照渡しを使うとネスト構造になりますが、正直どういう処理が行われてそうなるのかよく理解できておりません。
|
4
7
|
公式などドキュメントは読みましたが、わかったようなわからないような…。
|
5
8
|
以下のコードで参照渡しを使うことで、なぜネストにできるのか、かみ砕いて説明していただけないでしょうか。
|
6
9
|
```
|
10
|
+
親子関係をもつデータの一覧を整形
|
11
|
+
/* 親子関係の配列を作る
|
12
|
+
* @param array $definitionList
|
13
|
+
* @return array
|
14
|
+
*/
|
15
|
+
private function createNest(array $definitionList): array
|
16
|
+
{
|
17
|
+
$newList = [];
|
18
|
+
foreach ($definitionList as $def) {
|
19
|
+
$newList[$def->getId()] = [
|
20
|
+
'id'=>$def->getId(),
|
21
|
+
'definition'=>$def->getName(),
|
22
|
+
'parentDataId'=>($def->getParentData() ? $def->getParentmData()->getId() : ''),
|
23
|
+
}
|
24
|
+
$nests = $this->createNestRecursive($newList);
|
25
|
+
return $nests;
|
26
|
+
}
|
27
|
+
|
28
|
+
```
|
29
|
+
※$definitionListはDBから取得したデータのArrayCollectionで内部に自身のIDと親データのIDを持っています。
|
30
|
+
```
|
31
|
+
//ツリー構造を作る。
|
32
|
+
private function createNestRecursive(array $newList)
|
33
|
+
{
|
7
|
-
$tree = [];
|
34
|
+
$tree = [];
|
8
35
|
$index = [];
|
9
|
-
foreach ($
|
36
|
+
foreach ($newList as $id=>$data) {
|
10
37
|
$index[$id] = [
|
11
38
|
'id' => $id,
|
12
|
-
'parent' => $data['
|
39
|
+
'parent' => $data['parentDataId'],
|
13
40
|
//子を保持するための配列
|
14
41
|
'children' => [],
|
15
|
-
'data' => $data['data']
|
16
42
|
];
|
17
43
|
}
|
18
44
|
foreach ($index as $key=>$value) {
|
19
|
-
if (array_key_exists($value['
|
45
|
+
if (array_key_exists($value['parentDataId'], $index) && $value['parentDataId'] != $value['id']) {
|
20
|
-
$index[$value['
|
46
|
+
$index[$value['parentDataId']]['children'][] = &$index[$key];
|
21
47
|
} else {
|
22
48
|
$tree[] = &$index[$key];
|
23
49
|
}
|
24
50
|
}
|
25
51
|
return $tree;
|
52
|
+
}
|
26
53
|
```
|