日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

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

發布時間:2025/3/20 49 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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;

?>

相關網頁

總結

以上是生活随笔為你收集整理的php+json对象格式,PHP 创建对象来输出 JSON 格式的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。