回答編集履歴
2
chousei
test
CHANGED
@@ -30,9 +30,7 @@
|
|
30
30
|
|
31
31
|
$result=array_map(function($x,$y){
|
32
32
|
|
33
|
-
$x["index"
|
33
|
+
return array_merge($x,["index"=>0]);
|
34
|
-
|
35
|
-
return $x;
|
36
34
|
|
37
35
|
},$y=array_values(array_filter($arr,function($x){
|
38
36
|
|
@@ -43,8 +41,6 @@
|
|
43
41
|
|
44
42
|
|
45
43
|
$i=0;
|
46
|
-
|
47
|
-
|
48
44
|
|
49
45
|
while(true){
|
50
46
|
|
@@ -62,9 +58,7 @@
|
|
62
58
|
|
63
59
|
$result=array_merge($result,array_map(function($x) use($i){
|
64
60
|
|
65
|
-
$x["index"
|
61
|
+
return array_merge($x,["index"=>$i+1]);
|
66
|
-
|
67
|
-
return $x;
|
68
62
|
|
69
63
|
},array_filter($arr,function($x) use($indexs){
|
70
64
|
|
1
調整
test
CHANGED
@@ -1,3 +1,85 @@
|
|
1
1
|
データが膨大ならSQLなどで対応するのが現実的です。
|
2
2
|
|
3
3
|
いわゆる入れ子集合モデルというアプローチになります
|
4
|
+
|
5
|
+
|
6
|
+
|
7
|
+
# 参考
|
8
|
+
|
9
|
+
```PHP
|
10
|
+
|
11
|
+
$arr=[
|
12
|
+
|
13
|
+
['id' => 1, 'parent' => null],
|
14
|
+
|
15
|
+
['id' => 2, 'parent' => 1],
|
16
|
+
|
17
|
+
['id' => 3, 'parent' => 2],
|
18
|
+
|
19
|
+
['id' => 4, 'parent' => null],
|
20
|
+
|
21
|
+
['id' => 5, 'parent' => 4],
|
22
|
+
|
23
|
+
['id' => 6, 'parent' => 5],
|
24
|
+
|
25
|
+
['id' => 7, 'parent' => 5],
|
26
|
+
|
27
|
+
['id' => 8, 'parent' => 7],
|
28
|
+
|
29
|
+
];
|
30
|
+
|
31
|
+
$result=array_map(function($x,$y){
|
32
|
+
|
33
|
+
$x["index"]=0;
|
34
|
+
|
35
|
+
return $x;
|
36
|
+
|
37
|
+
},$y=array_values(array_filter($arr,function($x){
|
38
|
+
|
39
|
+
return is_null($x["parent"]);
|
40
|
+
|
41
|
+
})),array_keys($y));
|
42
|
+
|
43
|
+
|
44
|
+
|
45
|
+
$i=0;
|
46
|
+
|
47
|
+
|
48
|
+
|
49
|
+
while(true){
|
50
|
+
|
51
|
+
$indexs=array_map(function($x){
|
52
|
+
|
53
|
+
return $x["id"];
|
54
|
+
|
55
|
+
},array_filter($result,function($x) use($i){
|
56
|
+
|
57
|
+
return $x["index"]==$i;
|
58
|
+
|
59
|
+
}));
|
60
|
+
|
61
|
+
if(count($indexs)==0) break;
|
62
|
+
|
63
|
+
$result=array_merge($result,array_map(function($x) use($i){
|
64
|
+
|
65
|
+
$x["index"]=$i+1;
|
66
|
+
|
67
|
+
return $x;
|
68
|
+
|
69
|
+
},array_filter($arr,function($x) use($indexs){
|
70
|
+
|
71
|
+
return in_array($x["parent"],$indexs);
|
72
|
+
|
73
|
+
})));
|
74
|
+
|
75
|
+
$i++;
|
76
|
+
|
77
|
+
}
|
78
|
+
|
79
|
+
usort($result,function($x,$y){return $x["id"]-$y["id"];});
|
80
|
+
|
81
|
+
print_r($result);
|
82
|
+
|
83
|
+
|
84
|
+
|
85
|
+
```
|