我正在将API集成到我的网站,该网站可以使用数组编写代码时处理存储在对象中的数据。

我想要一个快捷方式将对象转换为数组的函数。


#1楼

当您从数据库中获取数据作为对象时,您可能想要这样做:

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

#2楼

此处发布的所有其他答案仅适用于公共属性。 这是一种使用反射和吸气剂处理类似JavaBeans的对象的解决方案:

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

#3楼

如果对象属性是公共的,则可以执行以下操作:

$array =  (array) $object;

如果它们是私有的或受保护的,则它们在阵列上将具有奇怪的键名。 因此,在这种情况下,您将需要以下功能:

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

#4楼

您可以依靠JSON编码/解码功能的行为,将深层嵌套的对象快速转换为关联数组:

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

#5楼

get_object_vars($obj)呢? 如果只想访问一个对象的公共属性,这似乎很有用。

参见get_object_vars


#6楼

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

#7楼

转换和删除烦人的星星:

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

可能会比使用反射便宜。


#8楼

这是将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;
}// ---------------------------------------------------------
// ---------------------------------------------------------

用法示例:

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

#9楼

自定义函数将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 arrayreturn $d;}
}

另一个将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 objectreturn $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);

#10楼

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

#11楼

采用:

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

它返回一个没有特殊字符和类名的数组。


#12楼

在这里,我制作了一个objectToArray()方法,该方法也适用于递归对象,例如当$objectA包含$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 。 如果找到了递归嵌套对象,它将被字符串**recursive**代替。 否则它将因无限循环而失败。


#13楼

要将对象转换为数组,只需将其显式转换:

$name_of_array = (array) $name_of_object;

#14楼

对“知识渊博”代码的一些改进

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


#15楼

首先,如果需要对象中的数组,则可能应该首先将数据构造为数组。 想一想。

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

#16楼

由于很多人由于无法动态访问对象的属性而发现了此问题,因此我只想指出您可以在PHP中执行此操作: $valueRow->{"valueName"}

在上下文中(已删除HTML输出以提高可读性):

$valueRows = json_decode("{...}"); // Rows of unordered values decoded from a JSON objectforeach ($valueRows as $valueRow) {foreach ($references as $reference) {if (isset($valueRow->{$reference->valueName})) {$tableHtml .= $valueRow->{$reference->valueName};}else {$tableHtml .= " ";}}
}

#17楼

您可以轻松地使用此函数来获得结果:

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

使用PHP 5或更高版本。


#18楼

这个答案只是本文不同答案的结合,但这是将具有简单值或数组的具有公共或私有属性的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;
}

#19楼

@ SpYk3HH的简短解决方案

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

#20楼

您也可以使用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);

#21楼

您还可以在PHP中创建一个函数来转换对象数组:

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

#22楼

从第一个Google命中“ 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 。


#23楼

只是打字

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

以这种方式进行类型转换不会对对象图进行深层转换,您需要应用空字节(如手册引用中所述)以访问任何非公共属性。 因此,这在投射StdClass对象或仅具有公共属性的对象时效果最佳。 为了快速又肮脏(您想要的),这很好。

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

  • 快速的PHP对象到数组的转换

#24楼

将类型转换为数组。

$arr =  (array) $Obj;

它将解决您的问题。


#25楼

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

$arrObj = array(yourReturnedObject);

您还可以使用以下方法向其添加新的键和值对:

$arrObj['key'] = value;

#26楼

我的建议是,如果您的对象中甚至包含私有成员,也可以:

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

#27楼

对于您的情况,如果您使用“装饰器”或“日期模型转换”模式,那是正确/美丽的。 例如:

您的模特

class Car {/** @var int */private $color;/** @var string */private $model;/** @var string */private $type;/*** @return int*/public function getColor(): int{return $this->color;}/*** @param int $color* @return Car*/public function setColor(int $color): Car{$this->color = $color;return $this;}/*** @return string*/public function getModel(): string{return $this->model;}/*** @param string $model* @return Car*/public function setModel(string $model): Car{$this->model = $model;return $this;}/*** @return string*/public function getType(): string{return $this->type;}/*** @param string $type* @return Car*/public function setType(string $type): Car{$this->type = $type;return $this;}
}

装饰器

class CarArrayDecorator
{/** @var Car */private $car;/*** CarArrayDecorator constructor.* @param Car $car*/public function __construct(Car $car){$this->car = $car;}/*** @return array*/public function getArray(): array{return ['color' => $this->car->getColor(),'type' => $this->car->getType(),'model' => $this->car->getModel(),];}
}

用法

$car = new Car();
$car->setType('type#');
$car->setModel('model#1');
$car->setColor(255);$carDecorator = new CarArrayDecorator($car);
$carResponseData = $carDecorator->getArray();

因此,它将是更美丽,更正确的代码。


#28楼

我认为使用特征存储对象到数组的转换逻辑是一个好主意。 一个简单的例子:

trait ArrayAwareTrait
{/*** Return list of Entity's parameters* @return array*/public function toArray(){$props = array_flip($this->getPropertiesList());return array_map(function ($item) {if ($item instanceof \DateTime) {return $item->format(DATE_ATOM);}return $item;},array_filter(get_object_vars($this), function ($key) use ($props) {return array_key_exists($key, $props);}, ARRAY_FILTER_USE_KEY));}/*** @return array*/protected function getPropertiesList(){if (method_exists($this, '__sleep')) {return $this->__sleep();}if (defined('static::PROPERTIES')) {return static::PROPERTIES;}return [];}
}class OrderResponse
{use ArrayAwareTrait;const PROP_ORDER_ID = 'orderId';const PROP_TITLE = 'title';const PROP_QUANTITY = 'quantity';const PROP_BUYER_USERNAME = 'buyerUsername';const PROP_COST_VALUE = 'costValue';const PROP_ADDRESS = 'address';private $orderId;private $title;private $quantity;private $buyerUsername;private $costValue;private $address;/*** @param $orderId* @param $title* @param $quantity* @param $buyerUsername* @param $costValue* @param $address*/public function __construct($orderId,$title,$quantity,$buyerUsername,$costValue,$address) {$this->orderId = $orderId;$this->title = $title;$this->quantity = $quantity;$this->buyerUsername = $buyerUsername;$this->costValue = $costValue;$this->address = $address;}/*** @inheritDoc*/public function __sleep(){return [static::PROP_ORDER_ID,static::PROP_TITLE,static::PROP_QUANTITY,static::PROP_BUYER_USERNAME,static::PROP_COST_VALUE,static::PROP_ADDRESS,];}/*** @return mixed*/public function getOrderId(){return $this->orderId;}/*** @return mixed*/public function getTitle(){return $this->title;}/*** @return mixed*/public function getQuantity(){return $this->quantity;}/*** @return mixed*/public function getBuyerUsername(){return $this->buyerUsername;}/*** @return mixed*/public function getCostValue(){return $this->costValue;}/*** @return string*/public function getAddress(){return $this->address;}
}$orderResponse = new OrderResponse(...);
var_dump($orderResponse->toArray());

#29楼

不是新的解决方案,但包括可用的toArray方法转换

function objectToArray($r)
{if (is_object($r)) {if (method_exists($r, 'toArray')) {return $r->toArray(); // returns result directly} else {$r = get_object_vars($r);}}if (is_array($r)) {$r = array_map(__FUNCTION__, $r); // recursive function call}return $r;
}

#30楼

这是一些代码:

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

将PHP对象转换为关联数组相关推荐

  1. PHP Object对象转换为Array数组

    在php中,Object对象转换为数组有三种方式:具体如下: 定义$testObject,为对象类型 1.简单转换:(array)$testObject: 2.通过自身函数进行转换:get_objec ...

  2. json对象(json对象和json数组)

    使用Struts2的json插件转换对象的配置问题Action 你好,你可以跟客服去咨询一下. java如果将一个文件变成json对象我有一个文件,需要通过ja google搜索gson 灰常好用的工 ...

  3. java jsonnode转_将JsonNode转换为java数组

    我正在使用websocket和JsonNode播放framewrok 2.前端通过使用websocket连接到播放框架后端.我将一个javascript数组转换成一个json节点,并通过使用websc ...

  4. php7 对象转数组,php7中为对象/关联数组进行解构赋值

    在CoffeeScript,Clojure,ES6和许多其他语言中,我们对对象/贴图/等进行了解构,如下所示: obj = {keyA: 'Hello from A', keyB: 'Hello fr ...

  5. php simplexmlelement array,php中SimpleXMLElement 对象转换为数组

    PHP 提供了 simplexml_load_string 方法用来解析 XML 格式的字符串,并返回 SimpleXMLElement 对象,不过一般数组是更为适用的,所以也会有转换为普通数组的需求 ...

  6. react中将json对象转换为数组

    json数据如下: 希望将其转换为如下数组: 要获得第一个属性,可以使用.reduce返回表示在对象中找到的属性的keys列表 要获得第二个,需要使用.map两次遍历数组中的每个项,每次都返回该项中定 ...

  7. php对象如何转化为数组,php如何将对象转换为数组

    php将对象转换为数组的方法是:可以先通过is_object()函数进行判断,然后进行强制类型转换.is_object()函数用于检测变量是否是一个对象.具体转换方法:[$arr = (array)( ...

  8. ajax字符串转数组对象数组,如何将AJAX返回的字符串转换为javascript数组对象

    我正在使用jqGrid并希望使用从ColdFusion返回的ajax来构建colModel数组.如何将AJAX返回的字符串转换为javascript数组对象 当我在下面的客户端上创建数组cm时,这可以 ...

  9. 对象数组转成字符串数组 java_如何在Java中将对象数组转换为字符串数组

    如何在Java中将对象数组转换为字符串数组 我使用以下代码将Object数组转换为String数组: Object Object_Array[]=new Object[100]; // ... get ...

最新文章

  1. python递归详解+汉诺塔小案例_汉诺塔,python递归实现解法步骤
  2. agilebpm脑图_干货基于SpringBoot2开发的Activiti引擎流程管理项目脚手架
  3. 【Qt】modbus之TCP模式写操作
  4. XP下Virtualbox虚拟Ubuntu共享文件夹
  5. java 垃圾回收机制_Java的垃圾回收机制
  6. quickServer介绍
  7. 实用技巧——获取验证码的倒计时
  8. android.support.v4.app.FragmentManager无法转换为android.app.FragmentManager
  9. c++ 等待子线程结束_进程和线程
  10. 磁力搜索引擎ZSKY一键安装包
  11. matlab实现模拟退火算法
  12. C#获取登录验证码图片
  13. 微型计算机增刊2016,科幻世界·2016年增刊
  14. 优秀新媒体文案的4种必备能力
  15. android emulator ps4,PS4 Simulator模拟器
  16. 36氪专访融云CEO董晗:8年企服,6年出海,现计划成为「沙特最大科技企业」
  17. android怎么美化ui,安卓教程第一期最终篇(转)systemui.apk最全修改美化
  18. 电脑卡在系统logo处
  19. ThinkPhp上传文件提示“没有上传的文件”解决方案
  20. WordCloud词云图去除停用词的正确方法

热门文章

  1. Tomcat 项目部署方式
  2. JQuery常用方法一览【转】
  3. (转)基于Ajax的应用程序架构汇总
  4. H5 --力导向图、关系图谱
  5. 如何在Qt Creator中导入图标资源
  6. 混淆Android JAR包的方法
  7. java if语句练习
  8. vs2012中对于entity framework的使用
  9. [置顶] Lucene开发实例(一般企业搜索平台完全够用全程)
  10. 构建 QC + QTP 自动化测试框架 2:QC 与 QTP 安装