Created
October 18, 2022 11:22
-
-
Save macsplit/0614d3175c732f8c0b34f4f5ec61cd32 to your computer and use it in GitHub Desktop.
Pretty Print PHP Object as JSON with Horizontal Alignment of Colons
This file contains hidden or 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 Encode Pretty Print with horizontal alignment of colons | |
json_encode( $obj, JSON_PRETTY_PRINT | JSON_NUMERIC_CHECK) | |
{ | |
"title": "languages", | |
"date": "2022-10-18", | |
"items": 2, | |
"draft": true, | |
"addendum": null, | |
"languages": [ | |
{ | |
"name": "python", | |
"designer": "Guido van Rossum", | |
"implementations": [ | |
"CPython", | |
"PyPy", | |
"Stackless Python", | |
"Jython" | |
] | |
}, | |
{ | |
"name": "ruby", | |
"designer": "Yukihiro Matsumoto", | |
"implementations": [ | |
"Ruby MRI", | |
"TruffleRuby", | |
"YARV", | |
"Rubinius" | |
] | |
} | |
] | |
} | |
jsonPrettyPrint( $obj ) | |
{ | |
"title" : "languages", | |
"date" : "2022-10-18", | |
"items" : 2, | |
"draft" : true, | |
"addendum" : null, | |
"languages" : [ | |
{ | |
"name" : "python", | |
"designer" : "Guido van Rossum", | |
"implementations" : [ | |
"CPython", | |
"PyPy", | |
"Stackless Python", | |
"Jython" | |
] | |
}, | |
{ | |
"name" : "ruby", | |
"designer" : "Yukihiro Matsumoto", | |
"implementations" : [ | |
"Ruby MRI", | |
"TruffleRuby", | |
"YARV", | |
"Rubinius" | |
] | |
} | |
] | |
} | |
*/ | |
function jsonPrettyPrint( $obj, $indent = 0, $tab = 3) | |
{ | |
$json = ""; | |
if (is_numeric($obj)) { | |
$json .= "$obj"; | |
} if (is_string($obj)) { | |
$json .= "\"$obj\""; | |
} else if (is_bool($obj)) { | |
$json .= ($obj) ? "true" : "false"; | |
} else if (is_null($obj)) { | |
$json .= "null"; | |
} else if (is_array($obj)) { | |
$json .= "[\n"; | |
$json .= str_repeat(" ", $indent); | |
$n = count($obj); | |
$i=0; | |
foreach ($obj as $val) { | |
$json .= str_repeat(" ", ($i) ? $indent+$tab : $tab); | |
$json .= jsonPrettyPrint($val, $indent + $tab, $tab); | |
if (++$i<$n) | |
$json .= ","; | |
$json .= "\n"; | |
} | |
$json .= str_repeat(" ", $indent); | |
$json .= "]"; | |
} else if (is_object($obj)) { | |
$json .= "{\n"; | |
$n = count(get_object_vars($obj)); | |
$i=0; | |
$max=0; | |
foreach ($obj as $key => $value) { | |
$max = max(strlen($key), $max); | |
} | |
foreach ($obj as $key => $val) { | |
$json .= str_repeat(" ", $indent+$tab); | |
$json .= "\"$key\""; | |
$json .= str_repeat(" ", $max - strlen($key)); | |
$json .= " : "; | |
$json .= jsonPrettyPrint($val, $indent + $tab, $tab); | |
if (++$i<$n) | |
$json .= ","; | |
$json .= "\n"; | |
} | |
$json .= str_repeat(" ", $indent); | |
$json .= "}"; | |
} | |
return $json; | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment