Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/svg/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php JSONSerializable-正确完成_Php_Json - Fatal编程技术网

Php JSONSerializable-正确完成

Php JSONSerializable-正确完成,php,json,Php,Json,我对php不太熟悉,所以这对你来说可能是个愚蠢的问题。我试着用谷歌搜索,但是没有找到我想要的方法 我有一个自定义类,我想使用PHP5.5中的JsonSerializable接口序列化为json。当前代码如下所示: class MyClass implements JsonSerializable { public $attr1; public $attr2; ..... public function jsonSerialize() { r

我对php不太熟悉,所以这对你来说可能是个愚蠢的问题。我试着用谷歌搜索,但是没有找到我想要的方法

我有一个自定义类,我想使用PHP5.5中的JsonSerializable接口序列化为json。当前代码如下所示:

class MyClass implements JsonSerializable
{
    public $attr1;
    public $attr2;
    .....

    public function jsonSerialize()
    {
       return array(
           'attr1' => $this->attr1,
           'attr2' => $this->attr2,
            ....
           );

    }
}
public function jsonSerialize()
{
    return get_object_vars($this);  
}
现在,如果对象中有20个实例变量,这看起来像是糟糕的代码,这就是为什么我要将此方法折射为如下内容:

class MyClass implements JsonSerializable
{
    public $attr1;
    public $attr2;
    .....

    public function jsonSerialize()
    {
       return array(
           'attr1' => $this->attr1,
           'attr2' => $this->attr2,
            ....
           );

    }
}
public function jsonSerialize()
{
    return get_object_vars($this);  
}
尽管get_object_vars应该返回一个关联数组('attr1'=>value1,…),但如果我想序列化一个对象数组,这将导致一个空json字符串:

$obj = new MyClass(..);
echo json_encode($obj); // this works. output: {"attr1":value1, ....}

$objarray = array(new MyClass(..), new MyClass(..));
echo json_encode($objarray); // this returns an empty string of length 0!
我做错了什么? 如果这是一个完全错误的做法,我很高兴得到任何提示:>

提前谢谢

//更新
几个小时后,我发现了问题。我从数据库创建对象数组,但dit未设置
charset=utf8
。由于json_encode无法处理其他字符集,因此它不返回任何内容。

您是否尝试在最后一步中反转您的逻辑?JSON在将每个对象添加到数组之前对其进行编码。我想你必须重新设置json大小才能得到你想要的外部数组。@Jasper:他想要的是对象数组,而不是字符串。@RocketHazmat
json\u encode
将返回对象的字符串表示,对吗?@Jasper:是的。这就是它的作用。你的代码对我有用: