3v4l.org

run code in 300+ PHP versions simultaneously
<?php function flatten($input_data, $path = "", $delimiter = ".", &$output = null) { if (is_null($output)) { $output = []; } if (is_array($input_data)) { if (isAssoc($input_data)) { array_push($output, [$path, new stdClass()]); foreach ($input_data as $key => $value) { if (!is_string($key)) { throw new Exception("Dictionary key must be a string, found " . gettype($key) . " instead."); } $new_key = $path ? $path . $delimiter . $key : $key; if (strpos($key, $delimiter) !== false) { throw new Exception("Key '{$key}' contains the delimiter '{$delimiter}'."); } flatten($value, $new_key, $delimiter, $output); } } else { array_push($output, [$path, []]); foreach ($input_data as $i => $value) { $new_key = $path ? $path . $delimiter . $i : strval($i); flatten($value, $new_key, $delimiter, $output); } } } else { array_push($output, [$path, $input_data]); } return $output; } function isAssoc(array $arr) { if (array() === $arr) return false; return array_keys($arr) !== range(0, count($arr) - 1); } function unflatten($array_data, $delimiter = '.') { $root = $array_data[0][1]; if (!is_array($root) && !is_object($root)) { return $root; } array_shift($array_data); foreach ($array_data as [$path, $value]) { $path_parts = explode($delimiter, $path); $target = &$root; foreach ($path_parts as $part) { if (is_numeric($part)) { $part = intval($part); } if (is_array($target)) { $target = &$target[$part]; } elseif (is_object($target)) { $target = &$target->$part; } else { // Handle error } } $target = $value; } return $root; } function test_flatten_unflatten() { $test_cases = [ [ 'input' => ['name' => 'John', 'age' => 30], 'expected_flatten' => [ ['', new stdClass()], ['name', 'John'], ['age', 30] ] ], [ 'input' => ['animals' => ['dog', 'cat']], 'expected_flatten' => [ ['', new stdClass()], ['animals', []], ['animals.0', 'dog'], ['animals.1', 'cat'] ] ], [ 'input' => 'hello', 'expected_flatten' => [ ['', 'hello'] ] ], [ 'input' => [], 'expected_flatten' => [ ['', []] ] ], [ 'input' => new stdClass(), 'expected_flatten' => [ ['', new stdClass()] ] ] ]; foreach ($test_cases as $i => $test_case) { $input = $test_case['input']; $expected_flatten = $test_case['expected_flatten']; $flattened = flatten($input); if ($flattened === $expected_flatten) { echo "Test case $i for flatten: Passed\n"; } else { echo "Test case $i for flatten: Failed\n"; print_r($flattened); } $unflattened = unflatten($flattened); if ($unflattened == $input) { echo "Test case $i for unflatten: Passed\n"; } else { echo "Test case $i for unflatten: Failed\n"; print_r($unflattened); } } } // Run the test test_flatten_unflatten(); ?>

preferences:
30.97 ms | 411 KiB | 5 Q