note 113219 added to function.json-encode

From: Date: Fri, 13 Sep 2013 17:45:58 +0000
Subject: note 113219 added to function.json-encode
Groups: php.notes 
Request: Send a blank email to php-notes+get-196253@lists.php.net to get a copy of this message
<?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: эта функция работает более точно и быстрее, чем указанная выше). ---- Server IP: 69.147.83.199 Probable Submitter: 37.54.95.85 ---- Manual Page -- http://php.net/manual/en/function.json-encode.php Edit -- https://master.php.net/note/edit/113219 Del: integrated -- https://master.php.net/note/delete/113219/integrated Del: useless -- https://master.php.net/note/delete/113219/useless Del: bad code -- https://master.php.net/note/delete/113219/bad+code Del: spam -- https://master.php.net/note/delete/113219/spam Del: non-english -- https://master.php.net/note/delete/113219/non-english Del: in docs -- https://master.php.net/note/delete/113219/in+docs Del: other reasons-- https://master.php.net/note/delete/113219 Reject -- https://master.php.net/note/reject/113219 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#196253) next »