php+json对象格式,PHP 创建对象来输出 JSON 格式

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;

?>

相关网页

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值