Skip to content

Commit 585dde9

Browse files
authored
Merge pull request #74 from quexpl/master
PHP: Recursive with for loop
2 parents 0603b14 + 0102973 commit 585dde9

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed

php/for_recursive.php

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
<?php
2+
$sections = [
3+
[
4+
"title" => "Getting started",
5+
"reset_lesson_position" => false,
6+
"lessons" => [
7+
["name" => "Welcome"],
8+
["name" => "Installation"],
9+
],
10+
],
11+
[
12+
"title" => "Basic operator",
13+
"reset_lesson_position" => false,
14+
"lessons" => [
15+
["name" => "Addition / Subtraction"],
16+
["name" => "Multiplication / Division"],
17+
],
18+
],
19+
[
20+
"title" => "Advanced topics",
21+
"reset_lesson_position" => true,
22+
"lessons" => [
23+
["name" => "Mutability"],
24+
["name" => "Immutability"],
25+
],
26+
],
27+
];
28+
29+
function append_position($item, $counter) {
30+
$item['position'] = $counter++;
31+
return [$item, $counter];
32+
}
33+
34+
function process_items($items, $depth, $counter) {
35+
for($i = 0; $i<count($items); $i++) {
36+
[$item, $counter[$depth]] = append_position(array_shift($items), $counter[$depth]);
37+
38+
if (!empty($item['lessons'])) {
39+
if ($item["reset_lesson_position"]) $counter[$depth+1] = 1;
40+
[$item['lessons'],, $counter] = process_items($item['lessons'], $depth+1, $counter);
41+
}
42+
43+
array_push($items, $item);
44+
}
45+
46+
return [$items, $depth, $counter];
47+
}
48+
49+
[$newSection] = process_items($sections, 0, [1, 1]);
50+
print_r($newSection);

0 commit comments

Comments
 (0)