Last active
February 27, 2019 00:43
-
-
Save ryzr/bbea0009fafc084d44f2b30ca7640ba1 to your computer and use it in GitHub Desktop.
Convert JSON string to PHP short-array
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 = <<<EOT | |
{"PASTE_YOUR":"JSON_HERE"} | |
EOT; | |
echo '[' . PHP_EOL; | |
jsonToArray(json_decode($json, true), 1); | |
echo ']'; | |
function jsonToArray($data, $indentLevel = 0) | |
{ | |
$keys = array_keys($data); | |
$shouldShowKey = array_keys($keys) !== $keys; | |
foreach ($data as $key => $value) { | |
$key = is_numeric($key) ? $key : "'$key'"; | |
if (is_array($value)) { | |
$keyPrefix = $shouldShowKey ? $key . ' => [' : '['; | |
echo str_repeat(" ", $indentLevel * 4) . $keyPrefix . PHP_EOL; | |
jsonToArray($value, $indentLevel + 1); | |
echo str_repeat(" ", $indentLevel * 4) . '],' . PHP_EOL; | |
} else { | |
$keyPrefix = $shouldShowKey ? "$key => " : ''; | |
if (! is_bool($value) && ! is_numeric($value)) { | |
$value = "'$value'"; | |
} | |
echo str_repeat(" ", $indentLevel * 4) . $keyPrefix . $value . ',' . PHP_EOL; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment