-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathjson_encode.php
More file actions
63 lines (62 loc) · 2.23 KB
/
json_encode.php
File metadata and controls
63 lines (62 loc) · 2.23 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
<?php
/**
* Implementation of function json_encode on PHP
*
* @author Alexander Muzychenko
* @link https://github.com/alexmuz/php-json
* @see http://php.net/json_encode
* @license GNU Lesser General Public License (LGPL) http://www.gnu.org/copyleft/lesser.html
*/
if (!function_exists('json_encode')) {
function json_encode($value)
{
if (is_int($value)) {
return (string)$value;
} elseif (is_string($value)) {
$value = str_replace(array('\\', '/', '"', "\r", "\n", "\b", "\f", "\t"),
array('\\\\', '\/', '\"', '\r', '\n', '\b', '\f', '\t'), $value);
$convmap = array(0x80, 0xFFFF, 0, 0xFFFF);
$result = "";
for ($i = mb_strlen($value) - 1; $i >= 0; $i--) {
$mb_char = mb_substr($value, $i, 1);
if (mb_ereg("&#(\\d+);", mb_encode_numericentity($mb_char, $convmap, "UTF-8"), $match)) {
$result = sprintf("\\u%04x", $match[1]) . $result;
} else {
$result = $mb_char . $result;
}
}
return '"' . $result . '"';
} elseif (is_float($value)) {
return str_replace(",", ".", $value);
} elseif (is_null($value)) {
return 'null';
} elseif (is_bool($value)) {
return $value ? 'true' : 'false';
} elseif (is_array($value)) {
$with_keys = false;
$n = count($value);
for ($i = 0, reset($value); $i < $n; $i++, next($value)) {
if (key($value) !== $i) {
$with_keys = true;
break;
}
}
} elseif (is_object($value)) {
$with_keys = true;
} else {
return '';
}
$result = array();
if ($with_keys) {
foreach ($value as $key => $v) {
$result[] = json_encode((string)$key) . ':' . json_encode($v);
}
return '{' . implode(',', $result) . '}';
} else {
foreach ($value as $key => $v) {
$result[] = json_encode($v);
}
return '[' . implode(',', $result) . ']';
}
}
}