如何将这样的数组转换为对象?
[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"
)
当前回答
世界上最好的方法:)
function arrayToObject($conArray)
{
if(is_array($conArray)){
/*
* Return array converted to object
* Using __FUNCTION__ (Magic constant)
* for recursive call
*/
return (object) array_map(__FUNCTION__, $conArray);
}else{
// Return object
return $conArray;
}
}
如果使用不同的方法,就会出现问题。这是最好的方法。你所见过的。
其他回答
它的方法很简单,这将为递归数组创建一个对象:
$object = json_decode(json_encode((object) $yourArray), FALSE);
我肯定会用这样一种干净的方式:
<?php
class Person {
private $name;
private $age;
private $sexe;
function __construct ($payload)
{
if (is_array($payload))
$this->from_array($payload);
}
public function from_array($array)
{
foreach(get_object_vars($this) as $attrName => $attrValue)
$this->{$attrName} = $array[$attrName];
}
public function say_hi ()
{
print "hi my name is {$this->name}";
}
}
print_r($_POST);
$mike = new Person($_POST);
$mike->say_hi();
?>
如果你提交:
你会得到这个:
我发现这更符合逻辑的比较以上的答案从对象应该用于他们的目的(封装可爱的小对象)。
此外,使用get_object_vars确保在被操纵的对象中没有创建额外的属性(您不希望汽车有姓,也不希望人有4个轮子)。
function object_to_array($data)
{
if (is_array($data) || is_object($data))
{
$result = array();
foreach ($data as $key => $value)
{
$result[$key] = object_to_array($value);
}
return $result;
}
return $data;
}
function array_to_object($data)
{
if (is_array($data) || is_object($data))
{
$result= new stdClass();
foreach ($data as $key => $value)
{
$result->$key = array_to_object($value);
}
return $result;
}
return $data;
}
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