PHP array_merge在类中返回null

问题描述 投票:0回答:1

为什么这段代码返回null? 我检查它,但没有错误,当我调用数组合并2默认数组像[“x”=>“y”,“foo”=>“bar”]它运作良好! 看到:

<?php
class ClassName
{
    private $dataArray = array();
    public function put($arr){
        $this->dataArray = array_merge($arr,$this->dataArray);
        return $this;
    }    
    public function run(){
        echo json_encode($this->dataArray);
    }
}

$json = new ClassName();

$json->Test->LastLog = '123456789123456';
$json->Password      = 'Mypassword';
$json->Dramatic      = 'Cat';
$json->Things        = array("HI" => 1, 2, 3);

$json->put($json)->run();
php json class
1个回答
0
投票

你传递了一个对象而不是数组尝试这个代码得到的结果:

$json->put((array)$json)->run();

输出是:

> {"\u0000ClassName\u0000dataArray":["Volvo XC90","BMW
> M4","MaclarenP1"],"Test":"123456789123456","Password":"Mypassword","Dramatic":"Cat","Things":{"HI":1,"0":2,"1":3},"0":"Volvo
> XC90","1":"BMW M4","2":"MaclarenP1"}

编辑如果你想通过这样的$json->Test->LastLog意味着你需要替换对象声明,如:

$json = new ClassName();

$json->Test = array('LastLog'=>'123456789123456');
$json->Password      = 'Mypassword';
$json->Dramatic      = 'Cat';
$json->Things        = array("HI" => 1, 2, 3);

因为在你的put函数中是array_merge期望数组但是你发送了一个json_object而不是数组。 (数组)就像json_decode ...示例:简单对象

$object = new StdClass;
$object->foo = 1;
$object->bar = 2;

var_dump( (array) $object );

输出:

array(2) {
  'foo' => int(1)
  'bar' => int(2)
} 
© www.soinside.com 2019 - 2024. All rights reserved.