如何将这样的数组转换为对象?
[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"
)
当前回答
我使用的一个(它是类成员):
const MAX_LEVEL = 5; // change it as needed
public function arrayToObject($a, $level=0)
{
if(!is_array($a)) {
throw new InvalidArgumentException(sprintf('Type %s cannot be cast, array expected', gettype($a)));
}
if($level > self::MAX_LEVEL) {
throw new OverflowException(sprintf('%s stack overflow: %d exceeds max recursion level', __METHOD__, $level));
}
$o = new stdClass();
foreach($a as $key => $value) {
if(is_array($value)) { // convert value recursively
$value = $this->arrayToObject($value, $level+1);
}
$o->{$key} = $value;
}
return $o;
}
其他回答
受到所有这些代码的启发,我尝试创建一个增强版本,支持:特定的类名,避免构造函数方法,'beans'模式和严格模式(仅设置现有属性):
class Util {
static function arrayToObject($array, $class = 'stdClass', $strict = false) {
if (!is_array($array)) {
return $array;
}
//create an instance of an class without calling class's constructor
$object = unserialize(
sprintf(
'O:%d:"%s":0:{}', strlen($class), $class
)
);
if (is_array($array) && count($array) > 0) {
foreach ($array as $name => $value) {
$name = strtolower(trim($name));
if (!empty($name)) {
if(method_exists($object, 'set'.$name)){
$object->{'set'.$name}(Util::arrayToObject($value));
}else{
if(($strict)){
if(property_exists($class, $name)){
$object->$name = Util::arrayToObject($value);
}
}else{
$object->$name = Util::arrayToObject($value);
}
}
}
}
return $object;
} else {
return FALSE;
}
}
}
你也可以通过在变量的左边添加(object)来创建一个新对象。
<?php
$a = Array
( 'status' => " text" );
var_dump($a);
$b = (object)$a;
var_dump($b);
var_dump($b->status);
http://codepad.org/9YmD1KsU
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;
}
我使用以下代码将Yaml文件关联数组解析为对象状态。
这将检查所有提供的数组中是否隐藏有对象,并将它们转换为对象。
/**
* Makes a config object from an array, making the first level keys properties a new object.
* Property values are converted to camelCase and are not set if one already exists.
* @param array $configArray Config array.
* @param boolean $strict To return an empty object if $configArray is not an array
* @return stdObject The config object
*/
public function makeConfigFromArray($configArray = [],$strict = true)
{
$object = new stdClass();
if (!is_array($configArray)) {
if(!$strict && !is_null($configArray)) {
return $configArray;
}
return $object;
}
foreach ($configArray as $name => $value) {
$_name = camel_case($name);
if(is_array($value)) {
$makeobject = true;
foreach($value as $key => $val) {
if(is_numeric(substr($key,0,1))) {
$makeobject = false;
}
if(is_array($val)) {
$value[$key] = $this->makeConfigFromArray($val,false);
}
}
if($makeobject) {
$object->{$name} = $object->{$_name} = $this->makeConfigFromArray($value,false);
}
else {
$object->{$name} = $object->{$_name} = $value;
}
}
else {
$object->{$name} = $object->{$_name} = $value;
}
}
return $object;
}
这将把yaml配置为
fields:
abc:
type: formfield
something:
- a
- b
- c
- d:
foo:
bar
到由以下数组组成的数组:
array:1 [
"fields" => array:1 [
"abc" => array:2 [
"type" => "formfield"
"something" => array:4 [
0 => "a"
1 => "b"
2 => "c"
3 => array:1 [
"d" => array:1 [
"foo" => "bar"
]
]
]
]
]
]
以…为目标:
{#325
+"fields": {#326
+"abc": {#324
+"type": "formfield"
+"something": array:4 [
0 => "a"
1 => "b"
2 => "c"
3 => {#328
+"d": {#327
+"foo": "bar"
}
}
]
}
}
}
我肯定会用这样一种干净的方式:
<?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个轮子)。