質問編集履歴

2

追記

2017/06/27 07:57

投稿

owqbpu
owqbpu

スコア13

test CHANGED
File without changes
test CHANGED
@@ -118,7 +118,7 @@
118
118
 
119
119
 
120
120
 
121
- ```
121
+ ```PHP
122
122
 
123
123
 
124
124
 
@@ -141,3 +141,97 @@
141
141
 
142
142
 
143
143
  ```
144
+
145
+
146
+
147
+ ### 追記
148
+
149
+ @mts10806さん
150
+
151
+ > 途中のソース
152
+
153
+
154
+
155
+ 半端ですがこちらです。`id => 5`が出来ていません。また、`catname`も出来ていません。
156
+
157
+ 引数の参照渡しについて今ひとつ理解できていませんが、これがわかりにくくさせてる気もしています。
158
+
159
+ 再帰処理は参照渡しが必要になってしまうものですか?returnで返したほうがわかりやすい気がしています。
160
+
161
+ 子要素を作る処理が2回出てきている(`'children' => []`を2箇所でしてる)ので、何か違うなとも思っています。
162
+
163
+
164
+
165
+ ```PHP
166
+
167
+
168
+
169
+ function recursive(&$result, $array) {
170
+
171
+ if ($array['parent'] === 0) {
172
+
173
+ $result[$array['id']] = [
174
+
175
+ 'name' => $array['name'],
176
+
177
+ 'children' => [],
178
+
179
+ ];
180
+
181
+ } else {
182
+
183
+ if (isset($result[$array['parent']])) {
184
+
185
+ $result[$array['parent']]['children'][$array['id']] = [
186
+
187
+ 'name' => $array['name'],
188
+
189
+ 'children' => [],
190
+
191
+ ];
192
+
193
+ } else {
194
+
195
+ foreach ($result as $array2) {
196
+
197
+ recursive($array2['children'], $array['parent']);
198
+
199
+ }
200
+
201
+ }
202
+
203
+ }
204
+
205
+ }
206
+
207
+
208
+
209
+ $original = [
210
+
211
+ ['id' => 1, 'parent' => 0, 'name' => 'aaaa'],
212
+
213
+ ['id' => 2, 'parent' => 0, 'name' => 'bbbb'],
214
+
215
+ ['id' => 3, 'parent' => 1, 'name' => 'cccc'],
216
+
217
+ ['id' => 4, 'parent' => 2, 'name' => 'dddd'],
218
+
219
+ ['id' => 5, 'parent' => 3, 'name' => 'eeee'],
220
+
221
+ ];
222
+
223
+
224
+
225
+ $result = [];
226
+
227
+ foreach ($original as $array) {
228
+
229
+ recursive($result, $array);
230
+
231
+ }
232
+
233
+ var_dump($result);
234
+
235
+
236
+
237
+ ```

1

追記

2017/06/27 07:57

投稿

owqbpu
owqbpu

スコア13

test CHANGED
File without changes
test CHANGED
@@ -1,4 +1,6 @@
1
1
  ###前提・実現したいこと
2
+
3
+ PHP初心者です。
2
4
 
3
5
  一次元の配列から、階層構造の配列を作成したいのですが再帰処理を使用したことがなく、うまく出来ずにいます。
4
6