note 113219 deleted from function.json-encode by crell
| From: | crell@php.net | Date: | Fri, 01 Jul 2022 19:24:04 +0000 |
| Subject: | note 113219 deleted from function.json-encode by crell | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-218831@lists.php.net to get a copy of this message | ||
Note Submitter: eep2004 at ukr dot net
----
<?php
// alternative json_encode
function _json_encode($val)
{
if (is_string($val)) return '"'.addslashes($val).'"';
if (is_numeric($val)) return $val;
if ($val === null) return 'null';
if ($val === true) return 'true';
if ($val === false) return 'false';
$assoc = false;
$i = 0;
foreach ($val as $k=>$v){
if ($k !== $i++){
$assoc = true;
break;
}
}
$res = array();
foreach ($val as $k=>$v){
$v = _json_encode($v);
if ($assoc){
$k = '"'.addslashes($k).'"';
$v = $k.':'.$v;
}
$res[] = $v;
}
$res = implode(',', $res);
return ($assoc)? '{'.$res.'}' : '['.$res.']';
}
?>
Example:
Array
(
[0] => 7
[1] => false
[2] => Array
(
['a'] => Array
(
[0] => 1
[1] => 2
[3] => Array
(
[1] => true
[2] => 6
[0] => 4
)
[4] => Array
(
[0] => 'b'
[1] => null
)
)
)
)
Result:
[7,false,{"a":{"0":1,"1":2,"3":{"1":true,"2":6,"0":4},"4":["b",null]}}]
This function is more accurate and faster than, for example, that one:
http://www.php.net/manual/ru/function.json-encode.php#89908
(RU: ÑÑа ÑÑнкÑÐ¸Ñ ÑабоÑÐ°ÐµÑ Ð±Ð¾Ð»ÐµÐµ
ÑоÑно и бÑÑÑÑее, Ñем
ÑÐºÐ°Ð·Ð°Ð½Ð½Ð°Ñ Ð²ÑÑе).