php+json对象格式,PHP 创建对象来输出 JSON 格式
PHP 想要輸出 JSON [{0 -> xxx, north -> ooo}],但是沒有對(duì)象(PHP: Objects),想要直接指定值,再使用 json_encode() 產(chǎn)生 JSON,可以使用 stdClass(); 來達(dá)成。
注:stdClass: Anonymous Objects
PHP 創(chuàng)建對(duì)象來輸出 JSON 格式
PHP 使用 stdClass() 的使用范例
$r = new stdClass();
$r->{'0'}? = '不分區(qū)';
$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"}]
?>
想要每個(gè)值都是不同數(shù)組,作法如下:
$r1 = new stdClass();
$r2 = new stdClass();
$r3 = new stdClass();
$r4 = new stdClass();
$r5 = new stdClass();
$r6 = new stdClass();
$r7 = new stdClass();
$r1->{'0'} = '不分區(qū)';
$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"}]
?>
感謝 和風(fēng)信使 提供的寫法:
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' => '不分區(qū)',
'north' => '北',
'east' => '東',
'west' => '西',
'middle' => '中',
'south' => '南',
],
];
echo encode_json($response) . PHP_EOL;
?>
相關(guān)網(wǎng)頁
總結(jié)
以上是生活随笔為你收集整理的php+json对象格式,PHP 创建对象来输出 JSON 格式的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Php无刷新修改url,history
- 下一篇: oracle更改归档日志路径,oracl