質問編集履歴

2

修正内容の文言に不備あったため修正

2018/08/10 13:52

投稿

jojo003
jojo003

スコア14

test CHANGED
File without changes
test CHANGED
@@ -54,7 +54,7 @@
54
54
 
55
55
  ```
56
56
 
57
- ※$definitionListはDBから取得したデータのArrayCollectionで内部に自身のIDと親データのIDを持っています。
57
+ ※$definitionListはDBから取得したArrayCollectionで内部に自身のIDと親データを持っています。
58
58
 
59
59
  ```
60
60
 

1

情報不足だったため、追記しました。ご迷惑をおかけしました。

2018/08/10 13:52

投稿

jojo003
jojo003

スコア14

test CHANGED
File without changes
test CHANGED
@@ -1,6 +1,12 @@
1
1
  初心者質問で申し訳ございませんが、phpの参照渡しについて教えてください。
2
2
 
3
3
  親子関係のあるデータをもとにツリー構造を作ろうと、いろいろ調べて以下のようなコードを書きました。
4
+
5
+
6
+
7
+ 参考にしたのはこちらのQiita記事です。
8
+
9
+ [リンク内容](https://qiita.com/ibarakidouji/items/52c0b41e10e8d9a981b9)
4
10
 
5
11
  たしかに参照渡しを使うとネスト構造になりますが、正直どういう処理が行われてそうなるのかよく理解できておりません。
6
12
 
@@ -10,23 +16,69 @@
10
16
 
11
17
  ```
12
18
 
19
+ 親子関係をもつデータの一覧を整形
20
+
21
+ /* 親子関係の配列を作る
22
+
23
+ * @param array $definitionList
24
+
25
+ * @return array
26
+
27
+ */
28
+
29
+ private function createNest(array $definitionList): array
30
+
31
+ {
32
+
33
+ $newList = [];
34
+
35
+ foreach ($definitionList as $def) {
36
+
37
+ $newList[$def->getId()] = [
38
+
39
+ 'id'=>$def->getId(),
40
+
41
+ 'definition'=>$def->getName(),
42
+
43
+ 'parentDataId'=>($def->getParentData() ? $def->getParentmData()->getId() : ''),
44
+
45
+ }
46
+
47
+ $nests = $this->createNestRecursive($newList);
48
+
49
+ return $nests;
50
+
51
+ }
52
+
53
+
54
+
55
+ ```
56
+
57
+ ※$definitionListはDBから取得したデータのArrayCollectionで内部に自身のIDと親データのIDを持っています。
58
+
59
+ ```
60
+
61
+ //ツリー構造を作る。
62
+
63
+ private function createNestRecursive(array $newList)
64
+
65
+ {
66
+
13
- $tree = [];
67
+     $tree = [];
14
68
 
15
69
  $index = [];
16
70
 
17
- foreach ($dataList as $id=>$data) {
71
+ foreach ($newList as $id=>$data) {
18
72
 
19
73
  $index[$id] = [
20
74
 
21
75
  'id' => $id,
22
76
 
23
- 'parent' => $data['parentId'],
77
+ 'parent' => $data['parentDataId'],
24
78
 
25
79
  //子を保持するための配列
26
80
 
27
81
  'children' => [],
28
-
29
- 'data' => $data['data']
30
82
 
31
83
  ];
32
84
 
@@ -34,9 +86,9 @@
34
86
 
35
87
  foreach ($index as $key=>$value) {
36
88
 
37
- if (array_key_exists($value['parent'], $index) && $value['parent'] != $value['id']) {
89
+ if (array_key_exists($value['parentDataId'], $index) && $value['parentDataId'] != $value['id']) {
38
90
 
39
- $index[$value['parent']]['children'][] = &$index[$key];
91
+ $index[$value['parentDataId']]['children'][] = &$index[$key];
40
92
 
41
93
  } else {
42
94
 
@@ -48,4 +100,6 @@
48
100
 
49
101
  return $tree;
50
102
 
103
+ }
104
+
51
105
  ```