如何将这样的数组转换为对象?
[128] => Array
(
[status] => "Figure A.
Facebook's horizontal scrollbars showing up on a 1024x768 screen resolution."
)
[129] => Array
(
[status] => "The other day at work, I had some spare time"
)
如何将这样的数组转换为对象?
[128] => Array
(
[status] => "Figure A.
Facebook's horizontal scrollbars showing up on a 1024x768 screen resolution."
)
[129] => Array
(
[status] => "The other day at work, I had some spare time"
)
当前回答
Code
此函数的工作原理与json_decode(json_encode($arr), false)相同。
function arrayToObject(array $arr)
{
$flat = array_keys($arr) === range(0, count($arr) - 1);
$out = $flat ? [] : new \stdClass();
foreach ($arr as $key => $value) {
$temp = is_array($value) ? $this->arrayToObject($value) : $value;
if ($flat) {
$out[] = $temp;
} else {
$out->{$key} = $temp;
}
}
return $out;
}
测试
测试1:平面阵列
$arr = ["a", "b", "c"];
var_export(json_decode(json_encode($arr)));
var_export($this->arrayToObject($arr));
输出:
array(
0 => 'a',
1 => 'b',
2 => 'c',
)
array(
0 => 'a',
1 => 'b',
2 => 'c',
)
测试2:对象数组
$arr = [["a" => 1], ["a" => 1], ["a" => 1]];
var_export(json_decode(json_encode($arr)));
var_export($this->arrayToObject($arr));
输出:
array(
0 => stdClass::__set_state(array('a' => 1,)),
1 => stdClass::__set_state(array('a' => 1,)),
2 => stdClass::__set_state(array('a' => 1,)),
)
array(
0 => stdClass::__set_state(array('a' => 1,)),
1 => stdClass::__set_state(array('a' => 1,)),
2 => stdClass::__set_state(array('a' => 1,)),
)
测试3:对象
$arr = ["a" => 1];
var_export(json_decode($arr));
var_export($this->arrayToObject($arr));
输出:
stdClass::__set_state(array('a' => 1,))
stdClass::__set_state(array('a' => 1,))
其他回答
容易:
$object = json_decode(json_encode($array));
例子:
$array = array(
'key' => array(
'k' => 'value',
),
'group' => array('a', 'b', 'c')
);
$object = json_decode(json_encode($array));
那么,以下是正确的:
$object->key->k === 'value';
$object->group === array('a', 'b', 'c')
据我所知,没有内置的方法可以做到这一点,但它就像一个简单的循环一样简单:
$obj= new stdClass();
foreach ($array as $k=> $v) {
$obj->{$k} = $v;
}
如果你需要递归地构建你的对象,你可以详细说明。
我也有这个问题,但我注意到json_decode将JSON数组转换为对象。
所以,我通过使用json_encode($PHPArray)来实现我的解决方案,它返回对象的JSON字符串,然后我用Json_decode($string)解码字符串,它将返回一个完美的结构化对象。 速记
$object = json_decode(json_encode($array));
Or
$jsonString = json_encode($array);
$object = json_decode($jsonString);
CakePHP有一个递归的Set::map类,基本上是将数组映射到对象。为了使对象看起来像你想要的样子,你可能需要改变数组的样子。
http://api.cakephp.org/view_source/set/#line-158
最坏的情况下,您可能会从这个函数中得到一些想法。
你也可以使用ArrayObject,例如:
<?php
$arr = array("test",
array("one"=>1,"two"=>2,"three"=>3),
array("one"=>1,"two"=>2,"three"=>3)
);
$o = new ArrayObject($arr);
echo $o->offsetGet(2)["two"],"\n";
foreach ($o as $key=>$val){
if (is_array($val)) {
foreach($val as $k => $v) {
echo $k . ' => ' . $v,"\n";
}
}
else
{
echo $val,"\n";
}
}
?>
//Output:
2
test
one => 1
two => 2
three => 3
one => 1
two => 2
three => 3