PHP 建立物件來輸出 JSON 格式

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

註:stdClass: Anonymous Objects

PHP 建立物件來輸出 JSON 格式

PHP 使用 stdClass() 的使用範例

  1. <?php
  2. $r = new stdClass();
  3. $r->{'0'= '不分區';
  4. $r->north  = '北';
  5. $r->east   = '東';
  6. $r->west   = '西';
  7. $r->middle = '中';
  8. $r->south  = '南';
  9. $response  = [$r];
  10. echo json_encode($response);
  11. // [{"0":"\u4e0d\u5206\u5340","north":"\u5317","east":"\u6771","west":"\u897f","middle":"\u4e2d","south":"\u5357"}]
  12. ?>

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

  1. <?php
  2. $r1 = new stdClass();
  3. $r2 = new stdClass();
  4. $r3 = new stdClass();
  5. $r4 = new stdClass();
  6. $r5 = new stdClass();
  7. $r6 = new stdClass();
  8. $r7 = new stdClass();
  9. $r1->{'0'} = '不分區';
  10. $r2->north = '北';
  11. $r3->east  = '東';
  12. $r4->west1 = '西';
  13. $r5->middle = '中';
  14. $r6->south  = '南';
  15. $response = [$r1, $r2, $r3, $r4, $r5, $r6];
  16. echo json_encode($response);
  17. // [{"0":"\u4e0d\u5206\u5340"},{"north":"\u5317"},{"east":"\u6771"},{"west1":"\u897f"},{"middle":"\u4e2d"},{"south":"\u5357"}]
  18. ?>

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

  1. <?php
  2. $r = array(
  3. 0 => stdClass::__set_state(array(
  4. '0' => '不分區',
  5. 'north' => '北',
  6. ),
  7. 1 => stdClass::__set_state(array(
  8. '0' => '不分區',
  9. 'north' => '北',
  10. )
  11. );
  12. ?>

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

  1. <?php
  2. if(!function_exists('encode_json')) {
  3.     function encode_json( $var ) {
  4.         static $options = null;
  5.         if (is_null($options)) {
  6.             $options = 0;
  7.             if (version_compare(PHP_VERSION, '5.3.3') >= 0)
  8.                 $options |= JSON_NUMERIC_CHECK;
  9.             if (version_compare(PHP_VERSION, '5.4.0') >= 0)
  10.                 $options |= JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE;
  11.         }
  12.         return json_encode($var, $options);
  13.     }
  14. }
  15. $response = [
  16.     [
  17.         '0' => '不分區',
  18.         'north' => '北',
  19.         'east' => '東',
  20.         'west' => '西',
  21.         'middle' => '中',
  22.         'south' => '南',
  23.     ],
  24. ];
  25. echo encode_json($response) . PHP_EOL;
  26. ?>

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

  1. <?php
  2. $obj1 = new \stdClass; // Instantiate stdClass object
  3. $obj2 = new class{}; // Instantiate anonymous class
  4. $obj3 = (object)[]; // Cast empty array to object
  5. var_dump($obj1); // object(stdClass)#1 (0) {}
  6. var_dump($obj2); // object(class@anonymous)#2 (0) {}
  7. var_dump($obj3); // object(stdClass)#3 (0) {}
  8. echo json_encode([
  9. new \stdClass,
  10. new class{},
  11. (object)[],
  12. ]);
  13. // Outputs: [{},{},{}]
  14. ?>

相關網頁

作者: Tsung

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

發表迴響

這個網站採用 Akismet 服務減少垃圾留言。進一步了解 Akismet 如何處理網站訪客的留言資料