Created
February 12, 2021 09:58
-
-
Save Nex-Otaku/eae179eb9835dac678159aa899aa9b12 to your computer and use it in GitHub Desktop.
2021-02-12 PHP_VRN Challenge
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// Есть вот такой json: https://api.jsonbin.io/b/600e00febca934583e41307f | |
// На самом деле, на него надо смотреть как на какой-то json, в котором может быть есть массивы и/или объекты. Какие-то. Есть ли они вообще и сколько их достоверно не известно. Известно только то, что на вход подается валидный json. | |
// Задача: вывести все пути к массивам. Конкатенация пути через точку. Например в примере выше ключ bookkeeping указывает не на массив, а на другой объект. Путь bookkeeping.contacts указывает тоже не на массив, а на объект, а вот bookkeeping.contacts.emails указывает на массив и это первый найденный путь. Задача найти их всех. | |
// Правильный ответ для этого примера по ссылке | |
// | |
//[ | |
// 'bookkeeping.contacts.pones', | |
// 'bookkeeping.contacts.emails', | |
// 'bookkeeping.staff.employees.full_time' | |
//] | |
function getPaths($node, $path): array | |
{ | |
if (is_array($node)) { | |
return [$path]; | |
} | |
if (!is_object($node)) { | |
return []; | |
} | |
$result = []; | |
foreach ($node as $key => $value) { | |
$keyPath = $path === '' ? $key : "{$path}.{$key}"; | |
$result = array_merge($result, getPaths($node->$key, $keyPath)); | |
} | |
return $result; | |
} | |
$json = <<<JSON | |
{"bookkeeping":{"contacts":{"pones":[123456789,234567890,345678901],"emails":["bookkeeping@acme.com"]},"staff":{"total":2,"employees":{"full_time":[{"name":"Sonoo","email":"sonoo@acme.com","salary":56000,"married":true},{"name":"Ram","email":"ram@acme.com","salary":65000,"married":true},{"name":"Bob","email":"dob@acme.com","salary":42000,"married":true}]}}}} | |
JSON; | |
$decoded = json_decode($json); | |
$paths = getPaths($decoded, ''); | |
var_dump($paths); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment