PHP 想要输出 JSON [{0 -> xxx, north -> ooo}],但是没有对象(PHP: Objects),想要直接指定值,再使用 json_encode() 产生 JSON,可以使用 stdClass(); 来达成。
注:stdClass: Anonymous Objects
PHP 创建对象来输出 JSON 格式
PHP 使用 stdClass() 的使用范例
$r = new stdClass();
$r->{'0'} = '不分区';
$r->north = '北';
$r->east = '东';
$r->west = '西';
$r->middle = '中';
$r->south = '南';
$response = [$r];
echo json_encode($response);
// [{"0":"\u4e0d\u5206\u5340","north":"\u5317","east":"\u6771","west":"\u897f","middle":"\u4e2d","south":"\u5357"}]
?>
想要每个值都是不同数组,作法如下:
$r1 = new stdClass();
$r2 = new stdClass();
$r3 = new stdClass();
$r4 = new stdClass();
$r5 = new stdClass();
$r6 = new stdClass();
$r7 = new stdClass();
$r1->{'0'} = '不分区';
$r2->north = '北';
$r3->east = '东';
$r4->west1 = '西';
$r5->middle = '中';
$r6->south = '南';
$response = [$r1, $r2, $r3, $r4, $r5, $r6];
echo json_encode($response);
// [{"0":"\u4e0d\u5206\u5340"},{"north":"\u5317"},{"east":"\u6771"},{"west1":"\u897f"},{"middle":"\u4e2d"},{"south":"\u5357"}]
?>
感谢 和风信使 提供的写法:
if(!function_exists('encode_json')) {
function encode_json( $var ) {
static $options = null;
if (is_null($options)) {
$options = 0;
if (version_compare(PHP_VERSION, '5.3.3') >= 0)
$options |= JSON_NUMERIC_CHECK;
if (version_compare(PHP_VERSION, '5.4.0') >= 0)
$options |= JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE;
}
return json_encode($var, $options);
}
}
$response = [
[
'0' => '不分区',
'north' => '北',
'east' => '东',
'west' => '西',
'middle' => '中',
'south' => '南',
],
];
echo encode_json($response) . PHP_EOL;
?>
相关网页