Created
January 22, 2017 05:58
-
-
Save Jeff-Russ/4b63c4c16ea6a587f1eb17ade96e3932 to your computer and use it in GitHub Desktop.
PHP: array to string pretty json or php format
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 | |
function array_string($arr,$opts='php') { | |
if (is_array($opts)) $opts['depth']++; | |
else { | |
if (!is_string($opts)) { | |
$in = $opts; | |
$opts = is_integer($in) ? "json" : 'php'; | |
if ($in) $opts .= " pretty print"; | |
} | |
$args = preg_split('/[^a-z0-9]/i', $opts); | |
if (in_array('json', $args)) | |
$opts = array('open'=>'{','close'=>'}','sep'=>': ', 'integers'=>false); | |
else $opts = array('open'=>'[','close'=>']','sep'=>' => ','integers'=>true); | |
if (!in_array('pretty', $args)) $opts = $opts + array('indent'=>'','eol'=>''); | |
else $opts = $opts + array('indent'=>' ','eol'=>"\n" ); | |
$opts['depth'] = 1; #starts at 1 | |
$opts['print'] = in_array('print', $args) || in_array('echo', $args) ? true:false; | |
} | |
end($arr); $last = key($arr); | |
$result = "$opts[open]$opts[eol]"; | |
foreach($arr as $k=>$v){ | |
$result .= str_repeat($opts['indent'],$opts['depth']); | |
if (!$opts['integers']) $result .= "\"$k\"$opts[sep]"; | |
else $result .= is_integer($k) ? " $k$opts[sep]" : "\"$k\"$opts[sep]"; | |
if (is_array($v)) $result .= array_string($v,$opts); | |
elseif(is_bool($v)) $result .= $v ? "true":"false"; | |
elseif(is_numeric($v)) $result .= $v; | |
else $result .= "\"".addslashes($v)."\""; | |
$result .= $last===$k ? $opts['eol'] : ", $opts[eol]"; | |
} | |
$opts['depth']--; | |
$result .= str_repeat($opts['indent'],$opts['depth']).$opts['close']; | |
if ($opts['depth']===0) { | |
$result .= $opts['eol']; | |
if ($opts['print']) echo $result; | |
} | |
return $result; | |
} | |
$arr = array( | |
"one"=>true, | |
"two", | |
"subarray"=>array( | |
array( | |
"string"=>"yo", | |
"float"=>1234.0000 | |
), | |
array( | |
'a string', | |
"time"=>6.022e23 | |
) | |
) | |
); | |
array_string($arr, 'json print'); | |
array_string($arr, 'json pretty print'); | |
echo "no output...\n"; | |
array_string($arr, 'json pretty'); | |
array_string($arr, 'json'); | |
array_string($arr, 'php pretty'); | |
array_string($arr, 'php'); | |
echo "end no output...\n"; | |
array_string($arr, 'php print'); | |
array_string($arr, 'php print print'); | |
echo "no output...\n"; | |
array_string($arr, 'php pretty'); | |
array_string($arr, 'php'); | |
array_string($arr, 'php pretty'); | |
array_string($arr, 'php'); | |
echo "end no output...\n"; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment