Gor*_*don 1313
只是强调它
$array = (array) $yourObject;
Run Code Online (Sandbox Code Playgroud)
来自http://www.php.net/manual/en/language.types.array.php
如果将对象转换为数组,则结果是一个数组,其元素是对象的属性.键是成员变量名,有一些值得注意的例外:整数属性是不可访问的; 私有变量的类名前置于变量名; 受保护的变量在变量名前面加上'*'.这些前置值在任一侧都有空字节.
示例:简单对象
$object = new StdClass;
$object->foo = 1;
$object->bar = 2;
var_dump( (array) $object );
Run Code Online (Sandbox Code Playgroud)
输出:
array(2) {
'foo' => int(1)
'bar' => int(2)
}
Run Code Online (Sandbox Code Playgroud)
示例:复杂对象
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 );
Run Code Online (Sandbox Code Playgroud)
输出(为清晰起见,编辑了\ 0s):
array(3) {
'\0Foo\0foo' => int(1)
'\0*\0bar' => int(2)
'baz' => class stdClass#2 (0) {}
}
Run Code Online (Sandbox Code Playgroud)
输出var_export
而不是var_dump
:
array (
'' . "\0" . 'Foo' . "\0" . 'foo' => 1,
'' . "\0" . '*' . "\0" . 'bar' => 2,
'baz' =>
stdClass::__set_state(array(
)),
)
Run Code Online (Sandbox Code Playgroud)
以这种方式进行类型转换不会对对象图进行深度转换,您需要应用空字节(如手册中所述)来访问任何非公共属性.因此,在仅使用公共属性转换StdClass对象或对象时,这种方法效果最佳.为了快速和肮脏(你要求的)它没关系.
另见这篇深入的博文:
Jef*_*den 312
您可以依靠JSON编码/解码函数的行为快速将深层嵌套对象转换为关联数组:
$array = json_decode(json_encode($nested_object), true);
Run Code Online (Sandbox Code Playgroud)
Mau*_*ycy 62
从第一次谷歌搜索" php对象到关联数组 "我们有这个:
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;
}
Run Code Online (Sandbox Code Playgroud)
Ram*_* K. 57
如果您的对象属性是公共的,您可以:
$array = (array) $object;
Run Code Online (Sandbox Code Playgroud)
如果它们是私有的或受保护的,它们将在阵列上具有奇怪的键名.因此,在这种情况下,您将需要以下功能:
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;
}
Run Code Online (Sandbox Code Playgroud)
Isi*_*ius 14
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());
Run Code Online (Sandbox Code Playgroud)
产量
array(2) {
["b"]=>
string(3) "two"
["Testc"]=>
int(1)
}
array(1) {
["b"]=>
string(3) "two"
}
Run Code Online (Sandbox Code Playgroud)
小智 12
这是一些代码:
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;
}
Run Code Online (Sandbox Code Playgroud)
Fra*_*ois 12
此处发布的所有其他答案仅适用于公共属性.这是一个使用反射和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;
}
Run Code Online (Sandbox Code Playgroud)
Joe*_*Joe 11
怎么样get_object_vars($obj)
?如果您只想访问对象的公共属性,似乎很有用.
http://www.php.net/function.get-object-vars
Ade*_*eel 10
键入将对象转换为数组.
$arr = (array) $Obj;
Run Code Online (Sandbox Code Playgroud)
它会解决你的问题.
小智 6
您可以轻松地使用此函数来获得结果:
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;
}
Run Code Online (Sandbox Code Playgroud)
使用PHP 5或更高版本。
小智 5
这是将PHP对象转换为关联数组的递归PHP函数:
// ---------------------------------------------------------
// ----- object_to_array_recursive --- 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_recursive($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_recursive($val);
}
else {
$res_arr[$akey] = (empty($val)) ? $empty : (string)$val;
}
$i++;
}
}
return $res_arr;
}
// ---------------------------------------------------------
// ---------------------------------------------------------
Run Code Online (Sandbox Code Playgroud)
用法示例:
// ---- Return associative array from object, ... use:
$new_arr1 = object_to_array_recursive($my_object);
// -- or --
// $new_arr1 = object_to_array_recursive($my_object, TRUE);
// -- or --
// $new_arr1 = object_to_array_recursive($my_object, 1);
// ---- Return numeric array from object, ... use:
$new_arr2 = object_to_array_recursive($my_object, FALSE);
Run Code Online (Sandbox Code Playgroud)
将 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;
}
}
Run Code Online (Sandbox Code Playgroud)
另一个将 Array 转换为 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;
}
}
Run Code Online (Sandbox Code Playgroud)
使用示例:
// 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);
Run Code Online (Sandbox Code Playgroud)
用:
function readObject($object) {
$name = get_class ($object);
$name = str_replace('\\', "\\\\", $name); // Outcomment this line, if you don't 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;
}
Run Code Online (Sandbox Code Playgroud)
它返回一个没有特殊字符和类名的数组。
小智 5
要将对象转换为数组,只需显式转换它
$name_of_array = (array) $name_of_object;
Run Code Online (Sandbox Code Playgroud)
首先,如果您需要对象中的数组,则可能应该首先将数据构造为数组。想一想。
不要使用foreach
语句或JSON转换。如果您打算这样做,那么您将再次使用数据结构,而不是对象。
如果您确实需要它,请使用面向对象的方法来编写干净且可维护的代码。例如:
对象作为数组
class PersonArray implements \ArrayAccess, \IteratorAggregate
{
public function __construct(Person $person) {
$this->person = $person;
}
// ...
}
Run Code Online (Sandbox Code Playgroud)
如果需要所有属性,请使用传输对象:
class PersonTransferObject
{
private $person;
public function __construct(Person $person) {
$this->person = $person;
}
public function toArray() {
return [
// 'name' => $this->person->getName();
];
}
}
Run Code Online (Sandbox Code Playgroud)
这个答案只是这篇文章的不同答案的联合,但它是将具有简单值或数组的公共或私有属性的 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;
}
Run Code Online (Sandbox Code Playgroud)
@SpYk3HH 的简短解决方案
function objectToArray($o)
{
$a = array();
foreach ($o as $k => $v)
$a[$k] = (is_array($v) || is_object($v)) ? objectToArray($v): $v;
return $a;
}
Run Code Online (Sandbox Code Playgroud)
您还可以在PHP中创建一个函数来转换对象数组:
function object_to_array($object) {
return (array) $object;
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1048104 次 |
最近记录: |