|
| 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