Skip to content

Instantly share code, notes, and snippets.

@kyptov
Created August 29, 2016 13:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kyptov/8985071754bfe266ce454bfa3c5dd85d to your computer and use it in GitHub Desktop.
Save kyptov/8985071754bfe266ce454bfa3c5dd85d to your computer and use it in GitHub Desktop.
Example how to pretty display decoded json in PHP. Keeps structure for bindings. By clicking on element it possible to get full path from top parent to the nested elements.
<?php
declare(strict_types = 1);
function isSequential($array)
{
return array_keys($array) === range(0, count($array) - 1);
}
function prettyArray($value, $is_last = true, $indent = 0)
{
$result = '';
$soft_indent = str_repeat('&nbsp;', 4);
if (is_array($value)) {
$result .= '<div>';
$is_sequential = isSequential($value);
$result .= '<div>';
$result .= str_repeat($soft_indent, $indent);
$result .= $is_sequential ? '[' : '{';
$result .= '</div>';
$indent++;
end($value);
$last_key = key($value);
foreach ($value as $key => $item) {
$result .= '<div data-key="' . $key . '">';
$result .= str_repeat($soft_indent, $indent);
if (!$is_sequential) {
$result .= '<span class="key">"' . $key . '":</span>&nbsp;';
}
$result .= prettyArray($item, $last_key === $key, $indent + 1);
$result .= '</div>';
}
$result .= '<div>';
$result .= str_repeat($soft_indent, $indent - 1);
$result .= $is_sequential ? ']' : '}';
$result .= $is_last ? '' : ',';
$result .= '</div>';
$result .= '</div>';
} else {
if (is_string($value)) {
$result .= '<span class="string">"' . $value . '"</span>';
} elseif (is_numeric($value)) {
$result .= '<span class="num">' . $value . '</span>';
} elseif (is_bool($value)) {
$result .= '<span class="boolean">' . var_export($value, true) . '</span>';
} else {
$result .= '<span class="null">' . var_export($value, true) . '</span>';
}
$result .= $is_last ? '' : ',';
}
return $result;
}
$test = [
'test1' => 1,
'test2' => [23, 54, 76],
'test3' => [
'value1' => null,
'value2' => false,
],
'test4' => 'string',
];
?>
<style>
.key {
color: red;
}
.string {
color: green;
}
</style>
<?= prettyArray($test); ?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment