string json_encode ( mixed $value [, int $options = 0 [, int $depth = 512 ]] )
$arr = array('a' => 'b' , 'b' => 'c');
echo json_encode($arr, JSON_PRETTY_PRINT);
echo "\n";
echo json_encode($arr);
{
"a": "b",
"b": "c"
}
{"a":"b","b":"c"}
$format = '["%s",%d,%b]';
$jsonstr= sprintf($format, '张三', 15 , false );
echo $jsonstr;
echo "\n";
$json=json_decode($jsonstr);
echo "\n";
print_r($json);
echo json_last_error_msg();
["张三丰",16,0]
Array
(
[0] => 张三丰
[1] => 16
[2] => 0
)
No errorr
$arr = ['北京'=>['a',123=>[] ],'热门'];
$arr = array('a' => 'b');
echo encode($arr);
function encode($data) {
switch ($type = gettype($data)) {
case 'NULL':
return 'null';
case 'boolean':
return ($data ? 'true' : 'false');
case 'integer':
case 'double':
case 'float':
return $data;
case 'string':
return '"' . addcslashes($data, "\r\n\t\"") . '"';
case 'object':
$data = get_object_vars($data);
case 'array':
$count = 0;
$indexed = array();
$associative = array();
foreach ($data as $key => $value) {
if($count !== NULL && (gettype($key) !== 'integer' || $count++ !== $key)) {
$count = NULL;
}
$one = encode($value);
$indexed[] = $one;
$associative[] = encode($key) . ':' . $one;
}
if ($count !== NULL) {
return '[' . implode(',', $indexed) . ']';
} else {
return '{' . implode(',', $associative) . '}';
}
default:
return ''; // Not supported
}
}