在 PHP 中的对象上使用 json_encode(不考虑范围)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4697656/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 14:00:53  来源:igfitidea点击:

Using json_encode on objects in PHP (regardless of scope)

phpjsonscoperedbean

提问by A. Rager

I'm trying to output lists of objects as json and would like to know if there's a way to make objects usable to json_encode? The code I've got looks something like

我正在尝试将对象列表输出为 json 并且想知道是否有办法使对象可用json_encode?我得到的代码看起来像

$related = $user->getRelatedUsers();
echo json_encode($related);

Right now, I'm just iterating through the array of users and individually exporting them into arrays for json_encodeto turn into usable json for me. I've already tried making the objects iterable, but json_encodejust seems to skip them anyway.

现在,我只是遍历用户数组并将它们单独导出到数组中,json_encode以便为我变成可用的 json。我已经尝试过使对象可迭代,但json_encode似乎还是跳过了它们。

edit: here's the var_dump();

编辑:这是 var_dump();

php > var_dump($a);
object(RedBean_OODBBean)#14 (2) {
  ["properties":"RedBean_OODBBean":private]=>
  array(11) {
    ["id"]=>
    string(5) "17972"
    ["pk_UniversalID"]=>
    string(5) "18830"
    ["UniversalIdentity"]=>
    string(1) "1"
    ["UniversalUserName"]=>
    string(9) "showforce"
    ["UniversalPassword"]=>
    string(32) ""
    ["UniversalDomain"]=>
    string(1) "0"
    ["UniversalCrunchBase"]=>
    string(1) "0"
    ["isApproved"]=>
    string(1) "0"
    ["accountHash"]=>
    string(32) ""
    ["CurrentEvent"]=>
    string(4) "1204"
    ["userType"]=>
    string(7) "company"
  }
  ["__info":"RedBean_OODBBean":private]=>
  array(4) {
    ["type"]=>
    string(4) "user"
    ["sys"]=>
    array(1) {
      ["idfield"]=>
      string(2) "id"
    }
    ["tainted"]=>
    bool(false)
    ["model"]=>
    object(Model_User)#16 (1) {
      ["bean":protected]=>
      *RECURSION*
    }
  }
}

and here's what json_encode gives me:

这是 json_encode 给我的:

php > echo json_encode($a);
{}

I ended up with just this:

我最终得到了这个:

    function json_encode_objs($item){   
        if(!is_array($item) && !is_object($item)){   
            return json_encode($item);   
        }else{   
            $pieces = array();   
            foreach($item as $k=>$v){   
                $pieces[] = "\"$k\":".json_encode_objs($v);   
            }   
            return '{'.implode(',',$pieces).'}';   
        }   
    }   

It takes arrays full of those objects or just single instances and turns them into json - I use it instead of json_encode. I'm sure there are places I could make it better, but I was hoping that json_encode would be able to detect when to iterate through an object based on its exposed interfaces.

它需要包含这些对象或单个实例的数组并将它们转换为 json - 我使用它而不是 json_encode。我确信有一些地方我可以让它变得更好,但我希望 json_encode 能够根据对象的公开接口检测何时迭代它。

采纳答案by Gabor de Mooij

In RedBeanPHP 2.0 there is a mass-export function which turns an entire collection of beans into arrays. This works with the JSON encoder..

在 RedBeanPHP 2.0 中有一个批量导出函数,可以将整个 bean 集合转换为数组。这适用于 JSON 编码器..

json_encode( R::exportAll( $beans ) );

回答by jondavidjohn

All the properties of your object are private. aka... not available outside their class's scope.

您对象的所有属性都是私有的。又名......在他们班级的范围之外不可用。

Solution for PHP < 5.4

PHP < 5.4 的解决方案

If you do want to serialize your private and protected object properties, you have to implement a JSON encoding function insideyour Class that utilizes json_encode()on a data structure you create for this purpose.

如果您确实想要序列化您的私有和受保护对象属性,您必须您的类中实现一个 JSON 编码函数,该函数利用json_encode()您为此目的创建的数据结构。

class Thing {
    ...
    public function to_json() {
        return json_encode(array(
            'something' => $this->something,
            'protected_something' => $this->get_protected_something(),
            'private_something' => $this->get_private_something()                
        ));
    }
    ...
}

Solution for PHP >= 5.4

PHP >= 5.4 的解决方案

Use the new JsonSerializableInterface to provide your own json representation to be used by json_encode

使用新JsonSerializable接口提供您自己的 json 表示以供使用json_encode

class Thing implements JsonSerializable {
    ...
    public function jsonSerialize() {
        return [
            'something' => $this->something,
            'protected_something' => $this->get_protected_something(),
            'private_something' => $this->get_private_something()
        ];
    }
    ...
}

A more detailed writeup

更详细的写法

回答by ilanco

In PHP >= 5.4.0 there is a new interface for serializing objects to JSON : JsonSerializable

在 PHP >= 5.4.0 中有一个用于将对象序列化为 JSON 的新接口:JsonSerializable

Just implement the interface in your object and define a JsonSerializablemethod which will be called when you use json_encode.

只需在您的对象中实现接口并定义一个JsonSerializable将在您使用时调用的方法json_encode

So the solutionfor PHP >= 5.4.0 should look something like this:

所以PHP >= 5.4.0的解决方案应该是这样的:

class JsonObject implements JsonSerializable
{
    // properties

    // function called when encoded with json_encode
    public function jsonSerialize()
    {
        return get_object_vars($this);
    }
}

回答by user2944142

Following code worked for me:

以下代码对我有用:

public function jsonSerialize()
{
    return get_object_vars($this);
}

回答by chrisfargen

I didn't see this mentioned yet, but beans have a built-in method called getProperties().

我还没有看到提到这一点,但是 bean 有一个名为getProperties().

So, to use it:

因此,要使用它:

// What bean do we want to get?
$type = 'book';
$id = 13;

// Load the bean
$post = R::load($type,$id);

// Get the properties
$props = $post->getProperties();

// Print the JSON-encoded value
print json_encode($props);

This outputs:

这输出:

{
    "id": "13",
    "title": "Oliver Twist",
    "author": "Charles Dickens"
}

Now take it a step further. If we have an array of beans...

现在更进一步。如果我们有一个bean数组......

// An array of beans (just an example)
$series = array($post,$post,$post);

...then we could do the following:

...然后我们可以执行以下操作:

  • Loop through the array with a foreachloop.

  • Replace each element (a bean) with an array of the bean's properties.

  • 用循环遍历数组foreach

  • 将每个元素(一个 bean)替换为 bean 属性的数组。

So this...

所以这...

foreach ($series as &$val) {
  $val = $val->getProperties();
}

print json_encode($series);

...outputs this:

...输出这个:

[
    {
        "id": "13",
        "title": "Oliver Twist",
        "author": "Charles Dickens"
    },
    {
        "id": "13",
        "title": "Oliver Twist",
        "author": "Charles Dickens"
    },
    {
        "id": "13",
        "title": "Oliver Twist",
        "author": "Charles Dickens"
    }
]

Hope this helps!

希望这可以帮助!

回答by Phoenix

I usually include a small function in my objects which allows me to dump to array or json or xml. Something like:

我通常在我的对象中包含一个小函数,它允许我转储到数组、json 或 xml。就像是:

public function exportObj($method = 'a')
{
     if($method == 'j')
     {
         return json_encode(get_object_vars($this));
     }
     else
     {
         return get_object_vars($this);
     }
}

either way, get_object_vars()is probably useful to you.

无论哪种方式,get_object_vars()都可能对您有用。

回答by Asahajit

$products=R::findAll('products');
$string = rtrim(implode(',', $products), ',');
echo $string;

回答by Andrei

Here is my way:

这是我的方法:

function xml2array($xml_data)
{
    $xml_to_array = [];

    if(isset($xml_data))
    {
        if(is_iterable($xml_data))
        {
            foreach($xml_data as $key => $value)
            {
                if(is_object($value))
                {
                    if(empty((array)$value))
                    {
                        $value = (string)$value;
                    }
                    else
                    {
                        $value = (array)$value;
                    }
                    $value = xml2array($value);
                }
                $xml_to_array[$key] = $value;
            }
        }
        else
        {
            $xml_to_array = $xml_data;
        }
    }

    return $xml_to_array;
}

回答by Greg

for an array of objects, I used something like this, while following the custom method for php < 5.4:

对于一组对象,我使用了这样的方法,同时遵循 php < 5.4 的自定义方法:

$jsArray=array();

//transaction is an array of the class transaction
//which implements the method to_json

foreach($transactions as $tran)
{
    $jsArray[]=$tran->to_json();
}

echo json_encode($jsArray);