X

PHP 建立物件來輸出 JSON 格式

PHP 想要輸出 JSON [{0 -> xxx, north -> ooo}],但是沒有物件(PHP: Objects),想要直接指定值,再使用 json_encode() 產生 JSON,可以使用 stdClass(); 來達成。

註:stdClass: Anonymous Objects

PHP 建立物件來輸出 JSON 格式

PHP 使用 stdClass() 的使用範例

<?php
$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"}]
?>

想要每個值都是不同陣列,作法如下:

<?php
$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"}]
?>

直接使用 stdClass 的屬性設定進去的方式 (不太建議)

<?php
$r = array(
    0 => stdClass::__set_state(array(
        '0' => '不分區',
        'north' => '北',
    ),
    1 => stdClass::__set_state(array(
        '0' => '不分區',
        'north' => '北',
    )
);
?>

感謝 和風信使 提供的寫法:

<?php
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;
?>

註:stdClass 是 PHP 內建 Object:PHP: Objects - Manual

<?php
$obj1 = new \stdClass; // Instantiate stdClass object
$obj2 = new class{}; // Instantiate anonymous class
$obj3 = (object)[]; // Cast empty array to object

var_dump($obj1); // object(stdClass)#1 (0) {}
var_dump($obj2); // object(class@anonymous)#2 (0) {}
var_dump($obj3); // object(stdClass)#3 (0) {}

echo json_encode([
    new \stdClass,
    new class{},
    (object)[],
]);

// Outputs: [{},{},{}]
?>

相關網頁

Tsung: 對新奇的事物都很有興趣, 喜歡簡單的東西, 過簡單的生活.
Related Post