Skip to content

Instantly share code, notes, and snippets.

@tluyben
Last active July 24, 2023 07:23
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 tluyben/b5e0121ff8e65767d566e34ee3f82c84 to your computer and use it in GitHub Desktop.
Save tluyben/b5e0121ff8e65767d566e34ee3f82c84 to your computer and use it in GitHub Desktop.
A php json encode that doesn't care about encoding.
function _json_encode($ar) {
$res = "";
if (is_array($ar)) {
if (count($ar)==0) {
return $res;
}
if (is_numeric(array_keys($ar)[0])) {
$res .= "\n[\n";
for($i=0;$i<count($ar);$i++) {
$v = $ar[$i];
$res .= _json_encode($v);
if ($i<count($ar)-1) $res.=",\n";
}
$res .= "\n]\n";
} else {
$res .= "\n{\n";
$keys = array_keys($ar);
for($i=0;$i<count($keys);$i++) {
$k = $keys[$i];
$v = $ar[$k];
$res .= '"'.$k.'"'.":"._json_encode($v);
if ($i<count($keys)-1) $res.=",\n";
}
$res .="\n}\n";
}
} else if (is_object($ar)) {
$res .= "\n{\n";
$keys = array_keys((array)$ar);
for($i=0;$i<count($keys);$i++) {
$k = $keys[$i];
$v = $ar[$k];
$res .= '"'.$k.'"'.":"._json_encode($v);
if ($i<count($keys)-1) $res.=",\n";
}
$res .="\n}\n";
} else {
$ar = str_replace('"','\"',$ar);
$ar = str_replace("\n", '\\n', $ar);
$res .= '"'.$ar.'"';
}
return $res;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment