将PHP对象转换为关联数组

我正在整合一个API到我的网站,它使用存储在对象中的数据,而我的代码是用数组写的。

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

只是forms化它

$array = (array) $yourObject; 

http://www.php.net/manual/en/language.types.array.php

如果一个对象被转换成一个数组,那么结果就是一个数组,其元素就是该对象的属性。 这些键是成员variables名,有一些值得注意的例外:整型属性是不可访问的; 私有variables具有名称前面的类名称; 受保护的variables在variables名前加了一个“*”。 这些前置的值在任何一方都有空字节。

示例:简单对象

 $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 ); 

输出(为清楚起见编辑了\ 0):

 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( )), ) 

通过这种方式进行types转换不会执行对象图的深度转换,而需要应用空字节(如手册引用中所述)来访问任何非公共属性。 所以当使用公共属性强制转换StdClass对象或对象时,效果最好。 对于快速和肮脏(你要求)这很好。

另请参阅这个深入的博客文章:

您可以通过依赖JSON编码/解码函数的行为快速将深度嵌套对象转换为关联数组:

 $array = json_decode(json_encode($nested_object), true); 

从第一次谷歌命中“ php对象assoc列阵 ”我们有这样的:

 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; } 

来源于codesnippets.joyent.com 。

如果你的对象属性是公开的,你可以这样做:

 $array = (array) $object; 

如果它们是私有的或受保护的,它们将在arrays上具有奇怪的密钥名称。 所以,在这种情况下,您将需要以下function:

 function dismount($object) { $reflectionClass = new ReflectionClass(get_class($object)); $array = array(); foreach ($reflectionClass->getProperties() as $property) { $property->setAccessible(true); $array[$property->getName()] = $property->getValue($object); $property->setAccessible(false); } return $array; } 

只要使用它,为multidimensional array

 $array = json_decode(json_encode($objects),TRUE); 

对于multidimensional array

 $array = json_decode(json_encode($objects),TRUE); 

我们可以简单地使用PHP的内置函数json_encode()和json_decode()来代替编写复杂的函数。

首先将对象转换为JSON,并将其作为数组取回。

json_decode()具有第二个参数:返回关联数组,将其设置为TRUE。

 $array = json_decode(json_encode($nested_object), true); 

在这里发布的所有其他答案只与公共属性。 下面是一个使用reflection和getter的类javabean对象的解决scheme:

 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; } 
 class Test{ const A = 1; public $b = 'two'; private $c = test::A; public function __toArray(){ return call_user_func('get_object_vars', $this); } } $my_test = new Test(); var_dump((array)$my_test); var_dump($my_test->__toArray()); 

产量

 array(2) { ["b"]=> string(3) "two" ["Testc"]=> int(1) } array(1) { ["b"]=> string(3) "two" } 

这里是一些代码:

 function object_to_array($data) { if ((! is_array($data)) and (! is_object($data))) return 'xxx'; //$data; $result = array(); $data = (array) $data; foreach ($data as $key => $value) { if (is_object($value)) $value = (array) $value; if (is_array($value)) $result[$key] = object_to_array($value); else $result[$key] = $value; } return $result; } 

怎么样get_object_vars($obj) ? 如果您只想访问对象的公共属性,看起来很有用。 http://www.php.net/function.get-object-vars

如果你不希望这个'*'被添加到你的数组中,你可以简单地做一些类似的事情

 $json = json_encode($object); $array = json_decode($json, true); print_r($array); 

这工作得很好,比types转换好得多。

嗨,

这里是我的recursionPHP函数将PHP对象转换为关联数组

 // --------------------------------------------------------- // ----- object_to_array_recusive --- function (PHP) ------- // --------------------------------------------------------- // --- arg1: -- $object = PHP Object - required --- // --- arg2: -- $assoc = TRUE or FALSE - optional --- // --- arg3: -- $empty = '' (Empty String) - optional --- // --------------------------------------------------------- // ----- return: Array from Object --- (associative) ------- // --------------------------------------------------------- function object_to_array_recusive ( $object, $assoc=TRUE, $empty='' ) { $res_arr = array(); if (!empty($object)) { $arrObj = is_object($object) ? get_object_vars($object) : $object; $i=0; foreach ($arrObj as $key => $val) { $akey = ($assoc !== FALSE) ? $key : $i; if (is_array($val) || is_object($val)) { $res_arr[$akey] = (empty($val)) ? $empty : object_to_array_recusive($val); } else { $res_arr[$akey] = (empty($val)) ? $empty : (string)$val; } $i++; } } return $res_arr; } // --------------------------------------------------------- // --------------------------------------------------------- 

用法示例:

 // ---- return associative array from object, ... use: $new_arr1 = object_to_array_recusive($my_object); // -- or -- // $new_arr1 = object_to_array_recusive($my_object,TRUE); // -- or -- // $new_arr1 = object_to_array_recusive($my_object,1); // ---- return numeric array from object, ... use: $new_arr2 = object_to_array_recusive($my_object,FALSE); 

自定义函数将stdClass转换为数组:

 function objectToArray($d) { if (is_object($d)) { // Gets the properties of the given object // with get_object_vars function $d = get_object_vars($d); } if (is_array($d)) { /* * Return array converted to object * Using __FUNCTION__ (Magic constant) * for recursive call */ return array_map(__FUNCTION__, $d); } else { // Return array return $d; } } 

另一个将数组转换为stdClass的自定义函数:

 function arrayToObject($d) { if (is_array($d)) { /* * Return array converted to object * Using __FUNCTION__ (Magic constant) * for recursive call */ return (object) array_map(__FUNCTION__, $d); } else { // Return object return $d; } } 

用法示例:

  // Create new stdClass Object $init = new stdClass; // Add some test data $init->foo = "Test data"; $init->bar = new stdClass; $init->bar->baaz = "Testing"; $init->bar->fooz = new stdClass; $init->bar->fooz->baz = "Testing again"; $init->foox = "Just test"; // Convert array to object and then object back to array $array = objectToArray($init); $object = arrayToObject($array); // Print objects and array print_r($init); echo "\n"; print_r($array); echo "\n"; print_r($object); 

要将对象转换为数组,只需将其明确地转换

 $name_of_array = (array) $name_of_object; 

你也可以在PHP中创build函数来转换对象数组。

 function object_to_array($object) { return (array) $object; } 

当您从数据库获取数据作为对象时,您可能需要这样做 – >

 // Suppose result is the end product from some query $query $result = $mysqli->query($query); $result = db_result_to_array($result); function db_result_to_array($result) { $res_array = array(); for ($count=0; $row = $result->fetch_assoc(); $count++) $res_array[$count] = $row; return $res_array; } 

types将您的对象转换为数组

 $arr = (array) $Obj; 

它会解决你的问题

 function readObject($object) { $name = get_class ($object); $name = str_replace('\\', "\\\\", $name); \\ Comment this line, if you dont use class namespaces approach in your project $raw = (array)$object; $attributes = array(); foreach ($raw as $attr => $val) { $attributes[preg_replace('('.$name.'|\*|)', '', $attr)] = $val; } return $attributes; } 

返回没有特殊字符和类名的数组

转换和删除恼人的星星:

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

可能它会比使用reflection更便宜。

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

不要使用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(); ]; } } 

这个函数可以将对象的完整性转换为数组关联

 function ObjetToArray($adminBar){ $reflector = new ReflectionObject($adminBar); $nodes = $reflector->getProperties(); $out=[]; foreach ($nodes as $node) { $nod=$reflector->getProperty($node->getName()); $nod->setAccessible(true); $out[$node->getName()]=$nod->getValue($adminBar); } return $out; } 

使用> = php5

对“良知”代码的一些推</s>

 /*** 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__

 $Menu = new Admin_Model_DbTable_Menu(); $row = $Menu->fetchRow($Menu->select()->where('id = ?', $id)); $Addmenu = new Admin_Form_Addmenu(); $Addmenu->populate($row->toArray()); 

在这里,我做了一个objectToArray()方法,它也适用于recursion对象,比如$objectA包含$objectB$objectB指向$objectA

此外,我已经使用ReflectionClass将输出限制到公共属性。 摆脱它,如果你不需要它。

  /** * Converts given object to array, recursively. * Just outputs public properties. * * @param object|array $object * @return array|string */ protected function objectToArray($object) { if (in_array($object, $this->usedObjects, TRUE)) { return '**recursive**'; } if (is_array($object) || is_object($object)) { if (is_object($object)) { $this->usedObjects[] = $object; } $result = array(); $reflectorClass = new \ReflectionClass(get_class($this)); foreach ($object as $key => $value) { if ($reflectorClass->hasProperty($key) && $reflectorClass->getProperty($key)->isPublic()) { $result[$key] = $this->objectToArray($value); } } return $result; } return $object; } 

为了识别已经使用的对象,我在这个(抽象)类中使用了一个名为$this->usedObjects的受保护属性。 如果find一个recursion的嵌套对象,它将被**recursive**replace。 否则由于无限循环会失败。

由于很多人find这个线程,因为dynamic访问一个对象的属性的麻烦,我只记得,你可以做到这一点在PHP:$ valueRow – > {“valueName”}

在上下文(删除HTML输出为了可读性):

 $valueRows = json_decode("{...}"); // rows of unordered values decoded from a json-object foreach($valueRows as $valueRow){ foreach($references as $reference){ if(isset($valueRow->{$reference->valueName})){ $tableHtml .= $valueRow->{$reference->valueName}; }else{ $tableHtml .= "&nbsp;"; } } } 

这个答案只是这篇文章的不同答案的联合,但它是一个解决scheme,使用公有或私有属性与简单的值或关联数组中的数组转换为PHP对象…

 function object_to_array($obj) { if (is_object($obj)) $obj = (array)$this->dismount($obj); if (is_array($obj)) { $new = array(); foreach ($obj as $key => $val) { $new[$key] = $this->object_to_array($val); } } else $new = $obj; return $new; } function dismount($object) { $reflectionClass = new \ReflectionClass(get_class($object)); $array = array(); foreach ($reflectionClass->getProperties() as $property) { $property->setAccessible(true); $array[$property->getName()] = $property->getValue($object); $property->setAccessible(false); } return $array; } 

@ SpYk3HH的简短解决scheme

 function objectToArray($o) { $a = array(); foreach ($o as $k => $v) $a[$k] = (is_array($v) || is_object($v)) ? objectToArray($v): $v; return $a; } 

你也可以使用Symfony串行器组件

 use Symfony\Component\Serializer\Encoder\JsonEncoder; use Symfony\Component\Serializer\Normalizer\ObjectNormalizer; use Symfony\Component\Serializer\Serializer; $serializer = new Serializer([new ObjectNormalizer()], [new JsonEncoder()]); $array = json_decode($serializer->serialize($object, 'json'), true); 

通过使用types转换,你可以解决你的问题。 只需将以下几行添加到您的返回对象:

 $arrObj = array(yourReturnedObject); 

您还可以使用以下方法将新的密钥和值对添加到它:

 $arrObj['key'] = value;