为什么此代码返回null?
我检查它,但没有错误,当我调用数组合并2默认数组像 [" x" =>" y"," foo& #34; =>" 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();
答案 0 :(得分: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)
}