我正在集成一个API到我的网站,它与存储在对象中的数据一起工作,而我的代码是使用数组编写的。

我想要一个快速和肮脏的函数将对象转换为数组。


当前回答

这里发布的所有其他答案都只使用公共属性。下面是一个使用反射和getter处理类javabean对象的解决方案:

function entity2array($entity, $recursionDepth = 2) {
    $result = array();
    $class = new ReflectionClass(get_class($entity));
    foreach ($class->getMethods(ReflectionMethod::IS_PUBLIC) as $method) {
        $methodName = $method->name;
        if (strpos($methodName, "get") === 0 && strlen($methodName) > 3) {
            $propertyName = lcfirst(substr($methodName, 3));
            $value = $method->invoke($entity);

            if (is_object($value)) {
                if ($recursionDepth > 0) {
                    $result[$propertyName] = $this->entity2array($value, $recursionDepth - 1);
                }
                else {
                    $result[$propertyName] = "***";  // Stop recursion
                }
            }
            else {
                $result[$propertyName] = $value;
            }
        }
    }
    return $result;
}

其他回答

从第一个谷歌点击“PHP对象到assoc数组”,我们有:

function object_to_array($data)
{
    if (is_array($data) || is_object($data))
    {
        $result = [];
        foreach ($data as $key => $value)
        {
            $result[$key] = (is_array($value) || is_object($value)) ? object_to_array($value) : $value;
        }
        return $result;
    }
    return $data;
}

来源是codesnippets.joyent.com。


与json_decode和json_encode的解决方案相比,这个解决方案似乎更快。下面是一个随机的基准测试(使用简单的时间测量):

$obj = (object) [
    'name'    =>'Mike',
    'surname' =>'Jovanson',
    'age'     =>'45',
    'time'    =>1234567890,
    'country' =>'Germany',
];

##### 100 000 cycles ######
* json_decode(json_encode($var))   : 4.15 sec
* object_to_array($var)            : 0.93 sec

只是对它进行类型转换

$array = (array) $yourObject;

从数组:

如果将一个对象转换为数组,则结果是一个数组,其元素是该对象的属性。键是成员变量名,但有几个明显的例外:整数属性不可访问;私有变量的类名在变量名之前;受保护变量的变量名前面有一个'*'。这些前置值的两边都是空字节。

示例:简单对象

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

var_dump( (array) $object );

输出:

array(2) {
  'foo' => int(1)
  'bar' => int(2)
}

示例:复杂对象

class Foo
{
    private $foo;
    protected $bar;
    public $baz;

    public function __construct()
    {
        $this->foo = 1;
        $this->bar = 2;
        $this->baz = new StdClass;
    }
}

var_dump( (array) new Foo );

输出(为清晰起见,编辑了\0s):

array(3) {
  '\0Foo\0foo' => int(1)
  '\0*\0bar' => int(2)
  'baz' => class stdClass#2 (0) {}
}

输出var_export而不是var_dump:

array (
  '' . "\0" . 'Foo' . "\0" . 'foo' => 1,
  '' . "\0" . '*' . "\0" . 'bar' => 2,
  'baz' =>
  stdClass::__set_state(array(
  )),
)

以这种方式进行类型转换不会对对象图进行深度转换,您需要应用null字节(如手册引用中所解释的那样)来访问任何非公共属性。因此,当强制转换StdClass对象或只有公共属性的对象时,这种方法效果最好。快速和肮脏(你所要求的)是可以的。

也可以看看这篇深入的博客文章:

快速PHP对象到数组的转换

首先,如果你需要一个来自对象的数组,你可能应该首先将数据构成一个数组。想想看。

不要使用foreach语句或JSON转换。如果您计划这样做,同样是在处理数据结构,而不是对象。

如果你真的需要它,可以使用面向对象的方法来获得干净和可维护的代码。例如:

对象作为数组

class PersonArray implements \ArrayAccess, \IteratorAggregate
{
    public function __construct(Person $person) {
        $this->person = $person;
    }
    // ...
 }

如果你需要所有的属性,使用一个传输对象:

class PersonTransferObject
{
    private $person;

    public function __construct(Person $person) {
        $this->person = $person;
    }

    public function toArray() {
        return [
            // 'name' => $this->person->getName();
        ];
    }

 }

转换和删除烦人的星星:

$array = (array) $object;
foreach($array as $key => $val)
{
    $new_array[str_replace('*_', '', $key)] = $val;
}

也许,它会比使用反射更便宜。

对“众所周知的”代码的一些改进

/*** mixed Obj2Array(mixed Obj)***************************************/ 
static public function Obj2Array($_Obj) {
    if (is_object($_Obj))
        $_Obj = get_object_vars($_Obj);
    return(is_array($_Obj) ? array_map(__METHOD__, $_Obj) : $_Obj);   
} // BW_Conv::Obj2Array

注意,如果函数是类的成员(如上所述),必须将__FUNCTION__更改为__METHOD__