Skip to content

Instantly share code, notes, and snippets.

@NickBeeuwsaert
Last active October 27, 2021 14:08
Show Gist options
  • Save NickBeeuwsaert/7568762 to your computer and use it in GitHub Desktop.
Save NickBeeuwsaert/7568762 to your computer and use it in GitHub Desktop.
PHP versions prior to 5.4 didn't have JSON_PRETTY_PRINT for json_encode, so here, I guess...
<?php
//PHP got the JSON_PRETTY_PRINT option for json_encode in 5.4, and I had to use a older version of PHP,
// So I made this
function json_pretty_encode($arr, $indent=" ", $characters=array(", ", ": "), $depth=0, $eol=PHP_EOL){
//You'd think that with the plethora of functions PHP has for array operations, they'd have one to check
// if an array is associative or not
// Now, I know what your saying "Oh, but, ALL arrays in PHP are associative!" Suck it, you know what I mean
$is_assoc = (array_keys($arr) !== range(0,count($arr)-1));
end($arr);
$last = key($arr);
$result = ($is_assoc?"{":"[").$eol; //Print whether or not the array is an object
foreach($arr as $key=>$val){
$result .= str_repeat($indent, $depth+1);//Indent it
if($is_assoc) // if is assocative, print the key name
$result .= "\"$key\"".$characters[1];
if(is_array($val)) //If the value is an array, encode that
$result .= json_pretty_encode($val, $indent, $characters, $depth+1, $eol);
else if(is_bool($val)) //ensure boolean values are printed as such
$result .= $val?"true":"false";
else if(is_numeric($val)) //Print out numbers
$result .= $val;
else //Everything else is a string
$result .= "\"".addslashes($val)."\"";
//if this is the last element just print a newline, otherwise print $characters[0]
$result .= (($key==$last)?"":$characters[0]).$eol;
}
$result .= str_repeat($indent, $depth).($is_assoc?"}":"]"); //Close the object
return $result;
}
//Test it...
$arr = array( "success"=>true,
"blah",
"results"=>array(
array(
"message"=>"blah",
"time"=>1234.0000
),
array(
"message"=>"Another message",
"time"=>6.022e23
)
)
);
print(json_pretty_encode($arr));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment