【问题标题】:PHP Object to JSON choosing properties [closed]PHP对象到JSON选择属性[关闭]
【发布时间】:2018-01-13 16:55:05
【问题描述】:

我想将一个对象转换为 JSON,并且可以选择要转换的属性。

<?php

class MyObject
{

    protected $id;
    protected $name;
    protected $sub1;
    protected $sub2;

    public function __construct($id, $name)
    {
        $this->id = $id;
        $this->name = $name;
        $this->sub1 = new MySubObject;
        $this->sub2 = new MySubObject;
    }

    public function json(array $array)
    {
        $arrayJson = array();
        foreach ($array as $value) {
            $arrayJson[$value] = $this->////////// HERE /////// ;
        }
        return json_encode($arrayJson);
    }

    public function debug()
    {
        echo '<pre>';
        var_dump($this);
        echo '</pre>';
    }

}

然后这样调用:

$MyObject= new MyObject(1, 'waffles');
$MyObject->debug();
echo $MyObject->json(array('id','name','sub1->x','sub2->z'));

调试输出:

object(Produto)#3 (3) {
  ["id":protected]=>
  string(1) "1"
  ["name":protected]=>
  string(6) "waffles"
  ["sub1":protected]=>
  object(MySubObject)#3 (3) {
    ["x"]=>
    1
    ["y"]=>
    2
    ["z"]=>
    3
  }
  ["sub2":protected]=>
  object(MySubObject)#3 (3) {
    ["x"]=>
    1
    ["y"]=>
    2
    ["z"]=>
    3
  }
}

我希望 JSON 的输出如下所示:

{ "id": 1,  "name": "waffles", "sub1": {"x": 1}, "sub2": {"z": 3} }

我在计算“json”函数时遇到了麻烦,也许这不是最好的方法。或者您可以通过选择要转换的字段来判断是否有其他方法可以将对象转换为 JSON。

我忘了说对象中可以有子对象。

【问题讨论】:

    标签: php json object


    【解决方案1】:

    你可能需要做这样的事情。请注意,这应该可以帮助您开始,您可以完成它以获得您想要的确切输出:

    public function json(array $array)
    {
        $arrayJson = array();
        foreach ($array as $key => $value) {
            # See if there is a relation
            if(strpos($value,'->') !== false) {
                # Explode and remove any empty fields
                $subobjexp = array_filter(explode('->',$value));
                # See if there is an internal param with this value
                if(isset($this->{$subobjexp[0]})) {
                    # Assign a shorthand variable
                    $arg    =   $this->{$subobjexp[0]};
                    # If there is a second arg, try and extract
                    if(isset($subobjexp[1]))
                        $arrayJson[$subobjexp[0]][$subobjexp[1]] = (!empty($arg->{$subobjexp[1]}))? $arg->{$subobjexp[1]} : false;
                }
            }
            else
                $arrayJson[$key] = $value;
        }
        return json_encode($arrayJson);
    }
    

    请注意,xz 等参数必须是 MySubObject 类中的公共变量,否则如果没有其他子类中的 get-type 方法,您将无法访问它们。

    【讨论】:

      【解决方案2】:

      拉斯克拉特的回答帮助我设置了这个功能。

      public function json(array $array)
      {
          $arrayJson = array();
          foreach ($array as $key => $value) {
              if (strpos($value, '->') !== false) {
                  $subobjexp = explode('->', $value);
                  $arr = array();
                  $ref = &$arr;
                  while ($key = array_shift($subobjexp)) {
                      $ref = &$ref[$key];
                  }
                  $subobjexp = explode('->', $value);
                  eval("\$ref = \$this->$value;");
                  $arrayJson[$subobjexp[0]] = $arr[$subobjexp[0]];
              } else {
                  eval("\$arrayJson[\$value] = \$this->$value;");
              }
      
          }
          return json_encode($arrayJson);
      }
      

      当然它还需要一些润色,我没有用足够的东西来显示错误。如果有人想指出错误或改进,谢谢。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-05-29
        相关资源
        最近更新 更多