Skip to content

Instantly share code, notes, and snippets.

@klapuch
Created May 5, 2021 08:28
Show Gist options
  • Save klapuch/e4736522e3a7224cb74b2dd7e9d4deba to your computer and use it in GitHub Desktop.
Save klapuch/e4736522e3a7224cb74b2dd7e9d4deba to your computer and use it in GitHub Desktop.
solution.php
<?php declare(strict_types=1);
$sections = json_decode(
<<<'JSON'
[
{
"title": "Getting started",
"reset_lesson_position": false,
"lessons": [
{"name": "Welcome"},
{"name": "Installation"}
]
},
{
"title": "Basic operator",
"reset_lesson_position": false,
"lessons": [
{"name": "Addition / Subtraction"},
{"name": "Multiplication / Division"}
]
},
{
"title": "Advanced topics",
"reset_lesson_position": true,
"lessons": [
{"name": "Mutability"},
{"name": "Immutability"}
]
}
]
JSON,
true,
);
$lessonPosition = 0;
$result = array_map(static function (array $section, int $sectionPosition) use (&$lessonPosition): array {
$lessonPosition = $section['reset_lesson_position'] ? 0 : $lessonPosition;
return ['position' => $sectionPosition + 1] + ['lessons' => array_map(static function (array $lesson) use ($section, &$lessonPosition): array {
return ['position' => ++$lessonPosition] + $lesson;
}, $section['lessons'])] + $section;
}, $sections, array_keys($sections));
var_dump($result);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment