Calling Method of array of objects? - php

How can I call methods from an array of objects (that hold an array of objects). I read: Get array with results of object method on each item in an array of objects in PHP but could not get it.
Here is my testcode: the first object holds attributes, then an object holds a record of the multiple attributes.
/*--------------------------------- */
class SqliteAttribute {
private $_fieldname = '';
private $_fieldvalue = '';
private $_type = 'TEXT';
private $_key = true;
function __construct($fieldname, $fieldvalue, $text, $key) {
$this->_fieldname = $fieldname;
$this->_fieldvalue = $fieldvalue;
$this->_text = $text;
$this->_key = $key;
}
function AsArray() {
$tempArray = array('fieldname' => $this->_fieldname,
'fieldvalue' => $this->_fieldvalue,
'type' => $this->_type,
'key' => $this->_key
);
return $tempArray;
}
}
/*--------------------------------- */
class SqliteRecord {
private $_attributes = array();
function __construct() {
}
function AddAttribute($fieldname, $fieldvalue, $text, $key) {
$attribute = new SqliteAttribute($fieldname, $fieldvalue, $text, $key);
$this->attributes[] = $attribute;
var_dump($this->_attributes); // shows it!
}
function AsArray() {
$temp_array = array();
var_dump($this->_attributes); // shows nothing
foreach ($this->_attributes as $key => $value) {
$temp_array[] = $value->AsArray();
}
return $temp_array;
}
}
And I call it like this
function updateFiles($files, $rootpath) {
$recordset = new SqliteRecordSet;
foreach ($files as $file) {
$record = new SqliteRecord;
$record->AddAttribute('Path', $file[0], 'TEXT', true);
print_r($record->AsArray()); // shows nothing
}
$recordset->insertIfNotExist_index();
}

$this->attributes vs $this->_attributes
you should always develop code with error reporting set to E_ALL and display_errors on. php would have notified you of your mistake here.

Related

How to convert an Object to an array in PHP7? [duplicate]

I'm integrating an API to my website which works with data stored in objects while my code is written using arrays.
I'd like a quick-and-dirty function to convert an object to an array.
Just typecast it
$array = (array) $yourObject;
From Arrays:
If an object is converted to an array, the result is an array whose elements are the object's properties. The keys are the member variable names, with a few notable exceptions: integer properties are unaccessible; private variables have the class name prepended to the variable name; protected variables have a '*' prepended to the variable name. These prepended values have null bytes on either side.
Example: Simple Object
$object = new StdClass;
$object->foo = 1;
$object->bar = 2;
var_dump( (array) $object );
Output:
array(2) {
'foo' => int(1)
'bar' => int(2)
}
Example: Complex Object
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 );
Output (with \0s edited in for clarity):
array(3) {
'\0Foo\0foo' => int(1)
'\0*\0bar' => int(2)
'baz' => class stdClass#2 (0) {}
}
Output with var_export instead of var_dump:
array (
'' . "\0" . 'Foo' . "\0" . 'foo' => 1,
'' . "\0" . '*' . "\0" . 'bar' => 2,
'baz' =>
stdClass::__set_state(array(
)),
)
Typecasting this way will not do deep casting of the object graph and you need to apply the null bytes (as explained in the manual quote) to access any non-public attributes. So this works best when casting StdClass objects or objects with only public properties. For quick and dirty (what you asked for) it's fine.
Also see this in-depth blog post:
Fast PHP Object to Array conversion
You can quickly convert deeply nested objects to associative arrays by relying on the behavior of the JSON encode/decode functions:
$array = json_decode(json_encode($nested_object), true);
From the first Google hit for "PHP object to assoc array" we have this:
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;
}
The source is at codesnippets.joyent.com.
To compare it to the solution of json_decode & json_encode, this one seems faster. Here is a random benchmark (using the simple time measuring):
$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
If your object properties are public you can do:
$array = (array) $object;
If they are private or protected, they will have weird key names on the array. So, in this case you will need the following 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;
}
What about get_object_vars($obj)? It seems useful if you only want to access the public properties of an object.
See get_object_vars.
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());
Output
array(2) {
["b"]=>
string(3) "two"
["Testc"]=>
int(1)
}
array(1) {
["b"]=>
string(3) "two"
}
Type cast your object to an array.
$arr = (array) $Obj;
It will solve your problem.
Here is some code:
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;
}
All other answers posted here are only working with public attributes. Here is one solution that works with JavaBeans-like objects using reflection and getters:
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;
}
To convert an object into array just cast it explicitly:
$name_of_array = (array) $name_of_object;
You can also create a function in PHP to convert an object array:
function object_to_array($object) {
return (array) $object;
}
Use:
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;
}
It returns an array without special characters and class names.
You can easily use this function to get the result:
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;
}
Use PHP 5 or later.
Short solution of #SpYk3HH
function objectToArray($o)
{
$a = array();
foreach ($o as $k => $v)
$a[$k] = (is_array($v) || is_object($v)) ? objectToArray($v): $v;
return $a;
}
Here is my recursive PHP function to convert PHP objects to an associative array:
// ---------------------------------------------------------
// ----- 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;
}
// ---------------------------------------------------------
// ---------------------------------------------------------
Usage example:
// ---- 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);
Custom function to convert stdClass to an array:
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;
}
}
Another custom function to convert Array to 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;
}
}
Usage Example:
// 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);
First of all, if you need an array from an object you probably should constitute the data as an array first. Think about it.
Don't use a foreach statement or JSON transformations. If you're planning this, again you're working with a data structure, not with an object.
If you really need it use an object-oriented approach to have a clean and maintainable code. For example:
Object as array
class PersonArray implements \ArrayAccess, \IteratorAggregate
{
public function __construct(Person $person) {
$this->person = $person;
}
// ...
}
If you need all properties, use a transfer object:
class PersonTransferObject
{
private $person;
public function __construct(Person $person) {
$this->person = $person;
}
public function toArray() {
return [
// 'name' => $this->person->getName();
];
}
}
Also you can use The Symfony Serializer Component
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);
You might want to do this when you obtain data as objects from databases:
// 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;
}
This answer is only the union of the different answers of this post, but it's the solution to convert a PHP object with public or private properties with simple values or arrays to an associative array...
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;
}
Some impovements to the "well-knwon" code
/*** 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
Notice that if the function is member of a class (like above) you must change __FUNCTION__ to __METHOD__
For your case it was right/beautiful if you would use the "decorator" or "date model transformation" patterns. For example:
Your model
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;
}
}
Decorator
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(),
];
}
}
Usage
$car = new Car();
$car->setType('type#');
$car->setModel('model#1');
$car->setColor(255);
$carDecorator = new CarArrayDecorator($car);
$carResponseData = $carDecorator->getArray();
So it will be more beautiful and more correct code.
Converting and removing annoying stars:
$array = (array) $object;
foreach($array as $key => $val)
{
$new_array[str_replace('*_', '', $key)] = $val;
}
Probably, it will be cheaper than using reflections.
I use this (needed recursive solution with proper keys):
/**
* This method returns the array corresponding to an object, including non public members.
*
* If the deep flag is true, is will operate recursively, otherwise (if false) just at the first level.
*
* #param object $obj
* #param bool $deep = true
* #return array
* #throws \Exception
*/
public static function objectToArray(object $obj, bool $deep = true)
{
$reflectionClass = new \ReflectionClass(get_class($obj));
$array = [];
foreach ($reflectionClass->getProperties() as $property) {
$property->setAccessible(true);
$val = $property->getValue($obj);
if (true === $deep && is_object($val)) {
$val = self::objectToArray($val);
}
$array[$property->getName()] = $val;
$property->setAccessible(false);
}
return $array;
}
Example of usage, the following code:
class AA{
public $bb = null;
protected $one = 11;
}
class BB{
protected $two = 22;
}
$a = new AA();
$b = new BB();
$a->bb = $b;
var_dump($a)
Will print this:
array(2) {
["bb"] => array(1) {
["two"] => int(22)
}
["one"] => int(11)
}
There's my proposal, if you have objects in objects with even private members:
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;
}
Since a lot of people find this question because of having trouble with dynamically access attributes of an object, I will just point out that you can do this in PHP: $valueRow->{"valueName"}
In context (removed HTML output for readability):
$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 .= " ";
}
}
}
I think it is a nice idea to use traits to store object-to-array converting logic. A simple example:
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());
$Menu = new Admin_Model_DbTable_Menu();
$row = $Menu->fetchRow($Menu->select()->where('id = ?', $id));
$Addmenu = new Admin_Form_Addmenu();
$Addmenu->populate($row->toArray());
Here I've made an objectToArray() method, which also works with recursive objects, like when $objectA contains $objectB which points again to $objectA.
Additionally I've restricted the output to public properties using ReflectionClass. Get rid of it, if you don't need it.
/**
* 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;
}
To identify already used objects, I am using a protected property in this (abstract) class, named $this->usedObjects. If a recursive nested object is found, it will be replaced by the string **recursive**. Otherwise it would fail in because of infinite loop.
By using typecasting you can resolve your problem.
Just add the following lines to your return object:
$arrObj = array(yourReturnedObject);
You can also add a new key and value pair to it by using:
$arrObj['key'] = value;

how to recursively convert from multidimensional form array to the related entity objects

I'm trying to convert a multidimensional HTML form array to its related entity (database) object classes with one to many relations and nested one to many relations.
Consider the following input exmaple (human readable):
order[id]: 1
order[note]: test note
order[ordertime]: 13. Dez. 2018 09:01
order[position][0][id]: 1
order[position][0][ordernumber]: ADSF-11
order[position][0][price]: 45.99
order[position][0][supplier][id]: 1
order[position][0][supplier][name]: test supplier 1
order[position][1][id]: 2
order[position][1][ordernumber]: ADSF-12
order[position][1][price]: 50.99
order[position][1][supplier][id]: 2
order[position][1][supplier][name]: test supplier 2
order[customer][firstname]: Human
order[customer][surname]: Being
order[customer][billingAddress][id]: 1
order[customer][billingAddress][firstname]: Human 2
order[customer][billingAddress][surname]: Being 2
order[customer][billingAddress][street]: test street 1
order[customer][billingAddress][zip]: 99999
order[customer][billingAddress][city]: test city
order[customer][shippingAddress][id]: 2
order[customer][shippingAddress][firstname]: Human 3
order[customer][shippingAddress][surname]: Being 3
order[customer][shippingAddress][street]: test street 100
order[customer][shippingAddress][zip]: 88888
order[customer][shippingAddress][city]: test city 2
We got an abstract class with empty body called AbstractEntity which every entity extends and the entities have public member variables for simple types. For arrays its access is private there are setter methods as well as addXX methods to add one entry at the end of the array (that's why reflection is needed and why we have $method1 and $method2). Additionally it parses date and time from inernationalized string to DateTime.
I would like to access them as in ORM frameworks style like Doctrine like so:
$order->getPosition()[0]->getBillingAddress()->firstname
Here is my worker class that does the main stuff:
<?php
namespace MyApp\Ajax;
use MyApp\Entity\AbstractEntity;
use MyApp\Entity\Repository;
class AjaxRequest
{
private $inputType;
private $data;
private $formatter;
private $objMapping;
private $repo;
public function __construct()
{
$this->inputType = strtolower($_SERVER['REQUEST_METHOD']) === 'post' ? \INPUT_POST : \INPUT_GET;
$this->formatter = new \IntlDateFormatter(
'de_DE',
\IntlDateFormatter::LONG,
\IntlDateFormatter::SHORT,
null,
\IntlDateFormatter::GREGORIAN,
'd. MMM Y HH:mm'
);
$this->objMapping = array(
'order' => "MyApp\\Entity\\Order",
'position' => "MyApp\\Entity\\Article",
'supplier' => "MyApp\\Entity\\Supplier",
'customer' => "MyApp\\Entity\\User",
'billingAddress' => "MyApp\\Entity\\UserAddress",
'shippingAddress' => "MyApp\\Entity\\UserAddress"
);
$this->repo = new Repository();
}
public function save()
{
$obj = $this->convertRequestToObj('order');
$this->data['success'] = $this->repo->save($obj);
$this->data['data'] = $obj;
$this->jsonResponse();
}
private function jsonResponse()
{
header('Content-type: application/json');
echo json_encode(
array(
'success' => $this->data['success'],
'data' => $this->convertToPublicObjects($this->data['data'])
)
);
}
private function convertToPublicObjects($object)
{
$names = array();
if (is_object($object) && !$object instanceof \DateTimeInterface) {
$reflection = new \ReflectionClass($object);
$columns = $reflection->getProperties();
$methods = $reflection->getMethods(\ReflectionMethod::IS_PUBLIC);
foreach ($columns as $column) {
$colName = $column->getName();
$method1 = 'get' . ucfirst($colName);
$method2 = 'is' . ucfirst($colName);
try {
if ($column->isPublic()) {
$names[$colName] = $column->getValue($object);
} else {
if ($reflection->hasMethod($method1) && $this->checkPublicMethods($methods, $method1)) {
$names[$colName] = $object->{$method1}();
} else {
if ($reflection->hasMethod($method2) && $this->checkPublicMethods($methods, $method2)) {
$names[$colName] = $object->{$method2}();
}
}
}
} catch (\ReflectionException $ex) {
$names[$colName] = null;
} catch (\TypeError $exc) {
$names[$colName] = null;
}
if (array_key_exists($colName, $names) && is_object($names[$colName])) {
if ($names[$colName] instanceof \DateTimeInterface) {
$names[$colName] = $this->formatter->format($names[$colName]);
} else {
$names[$colName] = $this->convertToPublicObjects($names[$colName]);
}
} elseif (array_key_exists($colName, $names) && is_array($names[$colName])) {
array_walk_recursive($names[$colName], array($this, 'walkReturnArray'));
}
}
}
return $names;
}
private function walkReturnArray(&$item, $key)
{
if (is_object($item)) {
$item = $this->convertToPublicObjects($item);
}
}
/**
* #param \ReflectionMethod[] $methods
* #param string $method
*
* #return bool
*/
private function checkPublicMethods(array $methods, string $method)
{
$found = false;
foreach ($methods as $meth) {
if ($meth->getName() === $method) {
$found = true;
break;
}
}
return $found;
}
/**
* Converts ORM like objects from the request from arrays to objects.
*
* #param string $key
*
* #return AbstractEntity
*/
private function convertRequestToObj(string $key)
{
$ar = filter_input($this->inputType, $key, \FILTER_DEFAULT, \FILTER_REQUIRE_ARRAY);
$baseObj = new $this->objMapping[$key]();
$this->mapArrayToObj($ar, $baseObj);
return $baseObj;
}
private function mapArrayToObj(array $ar, AbstractEntity $baseObj)
{
foreach ($ar as $column => $value) {
$reflection = new \ReflectionClass($baseObj);
$method1 = 'add' . ucfirst($column);
$method2 = 'set' . ucfirst($column);
$methods = $reflection->getMethods(\ReflectionMethod::IS_PUBLIC);
if (is_array($value)) {
$newObj = new $this->objMapping[$column]();
$this->addObjectTo($methods, $method1, $method2, $baseObj, $newObj);
$reflection = new \ReflectionClass($newObj);
$methods = $reflection->getMethods(\ReflectionMethod::IS_PUBLIC);
foreach ($value as $subCol => $subVal) {
$method2 = 'set' . ucfirst($subCol);
if (is_array($subVal)) {
if (is_numeric($subCol)) {
$this->mapArrayToObj($subVal, $newObj);
}
} else {
$this->parseSimpleType($newObj, $column, $value, $methods, $method2);
}
}
} else {
$this->parseSimpleType($baseObj, $column, $value, $methods, $method2);
}
}
}
private function parseSimpleType(AbstractEntity $obj, $column, $value, array $methods, $method2)
{
$timestamp = $this->formatter->parse($value);
if ($timestamp) {
try {
$value = new \DateTime($timestamp);
} catch (\Exception $ex) {
// nothing to do...
}
}
if ($this->checkPublicMethods($methods, $method2)) {
$obj->$method2($value);
} else {
$obj->{$column} = $value;
}
}
private function addObjectTo(array $methods, $method1, $method2, AbstractEntity $baseObj, AbstractEntity $newObj)
{
if ($this->checkPublicMethods($methods, $method1)) {
$baseObj->$method1($newObj);
} elseif ($this->checkPublicMethods($methods, $method2)) {
$baseObj->$method2($newObj);
} else {
$baseObj->{$column} = $newObj;
}
}
private function getNestedObject(AbstractEntity $obj, array $keys, $levelUp = 0)
{
if ($levelUp > 0) {
for ($i = 0; $i < $levelUp; $i++) {
unset($keys[count($keys) - 1]);
}
}
$innerObj = $obj;
$lastObj = $obj;
if (count($keys) > 0) {
foreach ($keys as $key) {
if (is_numeric($key)) {
$innerObj = $innerObj[$key];
} else {
$method = 'get' . ucfirst($key);
$reflection = new \ReflectionClass($innerObj);
$methods = $reflection->getMethods(\ReflectionMethod::IS_PUBLIC);
$lastObj = $innerObj;
if ($this->checkPublicMethods($methods, $method)) {
$innerObj = $innerObj->$method();
} else {
$innerObj = $innerObj->{$key};
}
}
}
if ($innerObj === null) {
$innerObj = $lastObj;
}
}
return $innerObj;
}
private function setNestedObject(array $parsedObjs, array $keys, AbstractEntity $objToAdd)
{
$ref = &$parsedObjs;
foreach ($keys as $key) {
$ref = &$ref[$key];
}
$ref = $objToAdd;
return $parsedObjs;
}
}
Let`s say this example calls the pubic method save. For some reason, it does the nesting wrong. Although the other way around, from objects to array using convertToPublicObjects works fine.
Here are my other tries:
With bypassed reference depth:
/**
* Converts ORM like objects from the request from arrays to objects.
*
* #param string $key
*
* #return AbstractEntity
*/
private function convertRequestToObj(string $key)
{
$ar = filter_input($this->inputType, $key, \FILTER_DEFAULT, \FILTER_REQUIRE_ARRAY);
$baseObj = new $this->objMapping[$key]();
$this->mapArrayToObj($ar, $baseObj, $baseObj);
return $baseObj;
}
private function mapArrayToObj(array $ar, AbstractEntity $baseObj, AbstractEntity $veryBaseObj, $refDepth = '')
{
foreach ($ar as $column => $value) {
$reflection = new \ReflectionClass($baseObj);
$method1 = 'add' . ucfirst($column);
$method2 = 'set' . ucfirst($column);
$methods = $reflection->getMethods(\ReflectionMethod::IS_PUBLIC);
if (is_array($value) && !is_numeric($column)) {
$refDepth .= $column .',';
$newObj = new $this->objMapping[$column]();
$this->addObjectTo($methods, $method1, $method2, $baseObj, $newObj);
$this->mapArrayToObj($value, $newObj, $veryBaseObj, $refDepth);
} elseif (is_array($value) && is_numeric($column)) {
$refDepth .= $column .',';
$refKeys = explode(',', substr($refDepth, 0, strrpos($refDepth, ',')));
$toAddObj = $this->getNestedObject($veryBaseObj, $refKeys);
$column = substr($refDepth, 0, strrpos($refDepth, ','));
$column = substr($column, 0, strrpos($column, ','));
$newObj = new $this->objMapping[$column]();
$this->addObjectTo($methods, $method1, $method2, $baseObj, $newObj);
$reflection = new \ReflectionClass($newObj);
$methods = $reflection->getMethods(\ReflectionMethod::IS_PUBLIC);
foreach ($value as $subCol => $subVal) {
if (is_array($subVal)) {
// sanitize strings like userMain,0,1,:
$refDepth = substr($refDepth, 0, strrpos($refDepth, ','));
$refDepth = substr($refDepth, 0, strrpos($refDepth, ',') + 1);
$refDepth .= $subCol . ',';
$this->mapArrayToObj($subVal, $newObj, $veryBaseObj, $refDepth);
} else {
$method2 = 'set' . ucfirst($subCol);
$this->parseSimpleType($newObj, $subCol, $subVal, $methods, $method2);
}
}
// sanitize strings like position,0,1,:
$refDepth = substr($refDepth, 0, strrpos($refDepth, ','));
$refDepth = substr($refDepth, 0, strrpos($refDepth, ',') + 1);
} else {
$refDepth = '';
$this->parseSimpleType($baseObj, $column, $value, $methods, $method2);
}
}
}
With if branches inside:
/**
* Converts ORM like objects from the request from arrays to objects.
*
* #param string $key
*
* #return AbstractEntity
*/
private function convertRequestToObj(string $key)
{
$ar = filter_input($this->inputType, $key, \FILTER_DEFAULT, \FILTER_REQUIRE_ARRAY);
$baseObj = new $this->objMapping[$key]();
$this->mapArrayToObj($ar, $baseObj, $baseObj);
return $baseObj;
}
private function mapArrayToObj(array $ar, AbstractEntity $baseObj, AbstractEntity $veryBaseObj, $refDepth = '')
{
foreach ($ar as $column => $value) {
$reflection = new \ReflectionClass($baseObj);
$method1 = 'add' . ucfirst($column);
$method2 = 'set' . ucfirst($column);
$methods = $reflection->getMethods(\ReflectionMethod::IS_PUBLIC);
if (is_array($value)) {
$refDepth .= $column .',';
$refDepthBackup = $refDepth;
$refKeys = explode(',', substr($refDepth, 0, strrpos($refDepth, ',')));
if (is_numeric($column)) {
$column = substr($refDepth, 0, strrpos($refDepth, ','));
$column = substr($column, 0, strrpos($column, ','));
$method1 = 'add' . ucfirst($column);
$toAddObj = $this->getNestedObject($veryBaseObj, $refKeys, 2);
// sanitize strings like position,0,1,:
$refDepth = substr($refDepth, 0, strrpos($refDepth, ','));
$refDepth = substr($refDepth, 0, strrpos($refDepth, ',') + 1);
} else {
$toAddObj = $baseObj;
}
$reflection = new \ReflectionClass($toAddObj);
$method1 = 'add' . ucfirst($column);
$method2 = 'set' . ucfirst($column);
$methods = $reflection->getMethods(\ReflectionMethod::IS_PUBLIC);
$newObj = new $this->objMapping[$column]();
$this->addObjectTo($methods, $method1, $method2, $toAddObj, $newObj);
$this->mapArrayToObj($value, $newObj, $veryBaseObj, $refDepthBackup);
} else {
$refDepth = '';
$this->parseSimpleType($baseObj, $column, $value, $methods, $method2);
}
}
}
With an inner foreach loop:
/**
* Converts ORM like objects from the request from arrays to objects.
*
* #param string $key
*
* #return AbstractEntity
*/
private function convertRequestToObj(string $key)
{
$ar = filter_input($this->inputType, $key, \FILTER_DEFAULT, \FILTER_REQUIRE_ARRAY);
$baseObj = new $this->objMapping[$key]();
$this->mapArrayToObj($ar, $baseObj);
return $baseObj;
}
private function mapArrayToObj(array $ar, AbstractEntity $baseObj)
{
foreach ($ar as $column => $value) {
$reflection = new \ReflectionClass($baseObj);
$method1 = 'add' . ucfirst($column);
$method2 = 'set' . ucfirst($column);
$methods = $reflection->getMethods(\ReflectionMethod::IS_PUBLIC);
if (is_array($value)) {
$newObj = new $this->objMapping[$column]();
$this->addObjectTo($methods, $method1, $method2, $baseObj, $newObj);
$reflection = new \ReflectionClass($newObj);
$methods = $reflection->getMethods(\ReflectionMethod::IS_PUBLIC);
foreach ($value as $subCol => $subVal) {
$method2 = 'set' . ucfirst($subCol);
if (is_array($subVal)) {
if (is_numeric($subCol)) {
$this->mapArrayToObj($subVal, $newObj);
}
} else {
$this->parseSimpleType($newObj, $column, $value, $methods, $method2);
}
}
} else {
$this->parseSimpleType($baseObj, $column, $value, $methods, $method2);
}
}
}
I have not worked with orm, so not sure if this is what you wanted.
Some hints:
I used php 5.6.30 so your milage may vary.
OOP is information hiding, that means teach each class what to do, no reflection.
Use fields to implement data driven framework
Implement magic get and call to dynamically access data and objects
Each class must validate its data, not implemented here
Each class must throw and catch its own exceptions, not implemented here
Use a factory pattern to create the data classes.
The interface defines the order class facade pattern.
The trait implements the default methods for all order classes.
I toyed with the idea of using XML classes, but this seems to work okay.
This is the class file that implements an order factory pattern. When creating model objects, use the factory class (static, do not instantiate) and don't instantiate the classes directly. The getValue() handles the factory::create when required. The result is the classes create themselves using the factory.
<?php /* ormorder.php */
// Object Relational Mapping (OrmOrder)
// order OrmOrder class interface methods
interface IORM
{
// function initFields(); // this should not be public?
function toArray();
function __get($name);
function __call($name,$value);
}
// order OrmOrder class trait methods
trait FORM
{
protected $fields;
protected $data;
function __construct($data)
{
parent::__construct();
$this->initFields();
$this->setData($data);
}
// always override, never call
protected function initFields(){ $this->fields = null;}
// sometimes override, never call
protected function setData($data)
{
foreach($this->fields as $field)
if(isset($data[$field]))
$this->data[$field] = $this->getValue($field,$data[$field]);
}
// seldom override, never call
protected function getValue($field,$data) { return $data; }
function toArray(){ return $this->data; }
final function __get($name)
{
if('data' == $name)
return $this->data;
return $this->data[$name];
}
function __call($name,$value)
{
$attr = $value[0];
$val = $value[1];
$result = null;
if(in_array($name, $this->fields))
if(isset($this->data[$name]))
if(is_array($this->data[$name]))
foreach($this->data[$name] as $obj)
if($obj->$attr == $val)
{
$result = $obj;
break;
}
else $result = $this->data[$name];
return $result;
}
}
// pacify php parent::_construct()
abstract
class ORMAbstract
{
function __construct() {}
}
// Main Order class that does (almost) everything
abstract
class Orm extends ORMAbstract implements IORM
{ use FORM;
}
// you should override getValue()
class Order extends Orm
{
}
class Position extends Orm
{
}
class Supplier extends Orm
{
}
class Customer extends Orm
{
}
class Address extends Orm
{
}
// static class to return OrmOrder objects
// keep factory in sync with classes
// Call directly never implement
class OrderFactory
{
static
function create($name, $data)
{
switch($name)
{
case 'supplier': return new Item($data);
case 'position': return new LineItem($data);
case 'address': return new Address($data);
case 'customer': return new Customer($data);
case 'order': return new Order($data);
default: return null;
}
}
}
?>
The model file (and main function). Run this from command prompt
/* assume php is properly setup */
> ordermodel
This file contains the top level model, the order model used to inspect the data. The toArray() returns a multidimensional array. The OrderModel class must be instantiated and passed the (html) multidimension array.
<?php /* ordermodel.php */
require_once('ormorder.php');
// sample database, development only, delete in production
$data['order'][0]['id'] = 0;
$data['order'][0]['note'] = 'test orders';
$data['order'][0]['date'] = '23 Mar 13';
$data['order'][0]['customer'][0]['id'] = 1;
$data['order'][0]['customer'][0]['account'] = '3000293826';
$data['order'][0]['customer'][0]['name'] = 'John Doe';
$data['order'][0]['customer'][0]['billing'][0] = 'Sand Castle';
$data['order'][0]['customer'][0]['billing'][1] = '1 beach street';
$data['order'][0]['customer'][0]['billing'][2] = 'strand';
$data['order'][0]['customer'][0]['billing'][3] = 'Lagoon';
$data['order'][0]['customer'][0]['billing'][4] = 'Fairy Island';
$data['order'][0]['customer'][0]['billing'][5] = '55511';
$data['order'][0]['customer'][0]['delivery'][0] = 'Nine Acres';
$data['order'][0]['customer'][0]['delivery'][1] = '3 corn field';
$data['order'][0]['customer'][0]['delivery'][2] = 'Butterworth';
$data['order'][0]['customer'][0]['delivery'][3] = 'Foam Vale';
$data['order'][0]['customer'][0]['delivery'][4] = 'Buttress Lake';
$data['order'][0]['customer'][0]['delivery'][5] = '224433';
$data['order'][0]['customer'][0]['items'][0]['supplier'] = '4000392292';
$data['order'][0]['customer'][0]['items'][0]['stock'] = '2000225571';
$data['order'][0]['customer'][0]['items'][0]['quantity'] = 5;
$data['order'][0]['customer'][0]['items'][0]['unitprice'] = 35.3;
$data['order'][0]['customer'][0]['items'][1]['supplier'] = '4000183563';
$data['order'][0]['customer'][0]['items'][1]['stock'] = '2000442279';
$data['order'][0]['customer'][0]['items'][1]['quantity'] = 12;
$data['order'][0]['customer'][0]['items'][1]['unitprice'] = 7.4;
// Top level Order management class
// could also be an OrmOrder class
class OrderModel
{
private $orders;
function __construct($data)
{
foreach($data['order'] as $order)
$this->orders[] = OrderFactory::create('order',$order);
}
function __call($name,$value)
{
$o = null;
$attribute = $value[0];
$val = $value[1];
foreach($this->orders as $order)
{
if($order->$attribute == $val)
{
$o = $order;
break;
}
}
return $o;
}
function toArray()
{
$data = null;
foreach($this->orders as $order)
$data['order'][] = $order->toArray();
return $data;
}
}
/* development only, delete in production */
function main($data)
{
$model = new OrderModel($data);
echo $model->order('id',12)->note;
var_dump($model->order('date',
'23 Mar 13')->customer('account','3000293826')->delivery->data);
// var_dump($model->toArray());
}
main($data);
?>
The output should be similar to:
PHP Notice: Trying to get property 'note' of non-object in C:\Users\Peter\Docum
ents\php\ordermodel.php on line 70
Notice: Trying to get property 'note' of non-object in C:\Users\Peter\Documents\
php\ordermodel.php on line 70
array(6) {
[0]=>
string(10) "Nine Acres"
[1]=>
string(12) "3 corn field"
[2]=>
string(11) "Butterworth"
[3]=>
string(9) "Foam Vale"
[4]=>
string(13) "Buttress Lake"
[5]=>
string(6) "224433"
}
Hopefully this does the kind of inspection you're looking for, probably not the same as Doctrine, but perhaps close enough to be useful.
UPDATE *
To implement the answer in your code try this:
<?PHP
require_once('ordermodel.php');
/*..... */
private function jsonResponse()
{
header('Content-type: application/json');
echo json_encode(
array(
'success' => $this->data['success'],
'data' => new OrderModel($this->data['data'])
)
);
}
?>

Passing an array to the magic get method

Out of curiosity, is there a way of passing an array in the magic get method. It has to be only the magic get method, or something equivalent. (But it shouldn't be using another function to go that)
For instance, IS THIS POSSIBLE?
<?php
// Book.php
Class Book{
/**
* Hold the book's details
* #var array
*/
private $book_details = [];
function __set($name, $value)
{
$book_list[$name] = $value;
}
function __get($name)
{
if (is_array($name)) {
$collect_info = [];
foreach ($this->book_details as $item => $value) {
if ($item == $name) {
$collect_info[$item] = $value;
}
}
return $collect_info;
} else {
return $this->book_details[$name];
}
}
}
and in another file like resourses.php
<?php
// resources.php
require_once "Book.php";
$book = new Book();
$book->name = "Somebook's Name";
$book->author = "This awesome dude";
$book->pages = "723";
$book->about = "Programming Content";
$book->name; // prints Somebook's Name
print_r($book->(["name", "pages"]));
// prints
// Array(
// [name] => Somebook's Name,
// [pages] => 723
// )

Foreach array php [duplicate]

I'm integrating an API to my website which works with data stored in objects while my code is written using arrays.
I'd like a quick-and-dirty function to convert an object to an array.
Just typecast it
$array = (array) $yourObject;
From Arrays:
If an object is converted to an array, the result is an array whose elements are the object's properties. The keys are the member variable names, with a few notable exceptions: integer properties are unaccessible; private variables have the class name prepended to the variable name; protected variables have a '*' prepended to the variable name. These prepended values have null bytes on either side.
Example: Simple Object
$object = new StdClass;
$object->foo = 1;
$object->bar = 2;
var_dump( (array) $object );
Output:
array(2) {
'foo' => int(1)
'bar' => int(2)
}
Example: Complex Object
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 );
Output (with \0s edited in for clarity):
array(3) {
'\0Foo\0foo' => int(1)
'\0*\0bar' => int(2)
'baz' => class stdClass#2 (0) {}
}
Output with var_export instead of var_dump:
array (
'' . "\0" . 'Foo' . "\0" . 'foo' => 1,
'' . "\0" . '*' . "\0" . 'bar' => 2,
'baz' =>
stdClass::__set_state(array(
)),
)
Typecasting this way will not do deep casting of the object graph and you need to apply the null bytes (as explained in the manual quote) to access any non-public attributes. So this works best when casting StdClass objects or objects with only public properties. For quick and dirty (what you asked for) it's fine.
Also see this in-depth blog post:
Fast PHP Object to Array conversion
You can quickly convert deeply nested objects to associative arrays by relying on the behavior of the JSON encode/decode functions:
$array = json_decode(json_encode($nested_object), true);
From the first Google hit for "PHP object to assoc array" we have this:
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;
}
The source is at codesnippets.joyent.com.
To compare it to the solution of json_decode & json_encode, this one seems faster. Here is a random benchmark (using the simple time measuring):
$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
If your object properties are public you can do:
$array = (array) $object;
If they are private or protected, they will have weird key names on the array. So, in this case you will need the following 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;
}
What about get_object_vars($obj)? It seems useful if you only want to access the public properties of an object.
See get_object_vars.
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());
Output
array(2) {
["b"]=>
string(3) "two"
["Testc"]=>
int(1)
}
array(1) {
["b"]=>
string(3) "two"
}
Type cast your object to an array.
$arr = (array) $Obj;
It will solve your problem.
Here is some code:
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;
}
All other answers posted here are only working with public attributes. Here is one solution that works with JavaBeans-like objects using reflection and getters:
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;
}
To convert an object into array just cast it explicitly:
$name_of_array = (array) $name_of_object;
You can also create a function in PHP to convert an object array:
function object_to_array($object) {
return (array) $object;
}
Use:
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;
}
It returns an array without special characters and class names.
You can easily use this function to get the result:
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;
}
Use PHP 5 or later.
Short solution of #SpYk3HH
function objectToArray($o)
{
$a = array();
foreach ($o as $k => $v)
$a[$k] = (is_array($v) || is_object($v)) ? objectToArray($v): $v;
return $a;
}
Here is my recursive PHP function to convert PHP objects to an associative array:
// ---------------------------------------------------------
// ----- 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;
}
// ---------------------------------------------------------
// ---------------------------------------------------------
Usage example:
// ---- 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);
Custom function to convert stdClass to an array:
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;
}
}
Another custom function to convert Array to 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;
}
}
Usage Example:
// 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);
First of all, if you need an array from an object you probably should constitute the data as an array first. Think about it.
Don't use a foreach statement or JSON transformations. If you're planning this, again you're working with a data structure, not with an object.
If you really need it use an object-oriented approach to have a clean and maintainable code. For example:
Object as array
class PersonArray implements \ArrayAccess, \IteratorAggregate
{
public function __construct(Person $person) {
$this->person = $person;
}
// ...
}
If you need all properties, use a transfer object:
class PersonTransferObject
{
private $person;
public function __construct(Person $person) {
$this->person = $person;
}
public function toArray() {
return [
// 'name' => $this->person->getName();
];
}
}
Also you can use The Symfony Serializer Component
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);
You might want to do this when you obtain data as objects from databases:
// 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;
}
This answer is only the union of the different answers of this post, but it's the solution to convert a PHP object with public or private properties with simple values or arrays to an associative array...
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;
}
Some impovements to the "well-knwon" code
/*** 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
Notice that if the function is member of a class (like above) you must change __FUNCTION__ to __METHOD__
For your case it was right/beautiful if you would use the "decorator" or "date model transformation" patterns. For example:
Your model
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;
}
}
Decorator
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(),
];
}
}
Usage
$car = new Car();
$car->setType('type#');
$car->setModel('model#1');
$car->setColor(255);
$carDecorator = new CarArrayDecorator($car);
$carResponseData = $carDecorator->getArray();
So it will be more beautiful and more correct code.
Converting and removing annoying stars:
$array = (array) $object;
foreach($array as $key => $val)
{
$new_array[str_replace('*_', '', $key)] = $val;
}
Probably, it will be cheaper than using reflections.
I use this (needed recursive solution with proper keys):
/**
* This method returns the array corresponding to an object, including non public members.
*
* If the deep flag is true, is will operate recursively, otherwise (if false) just at the first level.
*
* #param object $obj
* #param bool $deep = true
* #return array
* #throws \Exception
*/
public static function objectToArray(object $obj, bool $deep = true)
{
$reflectionClass = new \ReflectionClass(get_class($obj));
$array = [];
foreach ($reflectionClass->getProperties() as $property) {
$property->setAccessible(true);
$val = $property->getValue($obj);
if (true === $deep && is_object($val)) {
$val = self::objectToArray($val);
}
$array[$property->getName()] = $val;
$property->setAccessible(false);
}
return $array;
}
Example of usage, the following code:
class AA{
public $bb = null;
protected $one = 11;
}
class BB{
protected $two = 22;
}
$a = new AA();
$b = new BB();
$a->bb = $b;
var_dump($a)
Will print this:
array(2) {
["bb"] => array(1) {
["two"] => int(22)
}
["one"] => int(11)
}
There's my proposal, if you have objects in objects with even private members:
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;
}
Since a lot of people find this question because of having trouble with dynamically access attributes of an object, I will just point out that you can do this in PHP: $valueRow->{"valueName"}
In context (removed HTML output for readability):
$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 .= " ";
}
}
}
I think it is a nice idea to use traits to store object-to-array converting logic. A simple example:
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());
$Menu = new Admin_Model_DbTable_Menu();
$row = $Menu->fetchRow($Menu->select()->where('id = ?', $id));
$Addmenu = new Admin_Form_Addmenu();
$Addmenu->populate($row->toArray());
Here I've made an objectToArray() method, which also works with recursive objects, like when $objectA contains $objectB which points again to $objectA.
Additionally I've restricted the output to public properties using ReflectionClass. Get rid of it, if you don't need it.
/**
* 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;
}
To identify already used objects, I am using a protected property in this (abstract) class, named $this->usedObjects. If a recursive nested object is found, it will be replaced by the string **recursive**. Otherwise it would fail in because of infinite loop.
By using typecasting you can resolve your problem.
Just add the following lines to your return object:
$arrObj = array(yourReturnedObject);
You can also add a new key and value pair to it by using:
$arrObj['key'] = value;

Convert a PHP object to an associative array

I'm integrating an API to my website which works with data stored in objects while my code is written using arrays.
I'd like a quick-and-dirty function to convert an object to an array.
Just typecast it
$array = (array) $yourObject;
From Arrays:
If an object is converted to an array, the result is an array whose elements are the object's properties. The keys are the member variable names, with a few notable exceptions: integer properties are unaccessible; private variables have the class name prepended to the variable name; protected variables have a '*' prepended to the variable name. These prepended values have null bytes on either side.
Example: Simple Object
$object = new StdClass;
$object->foo = 1;
$object->bar = 2;
var_dump( (array) $object );
Output:
array(2) {
'foo' => int(1)
'bar' => int(2)
}
Example: Complex Object
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 );
Output (with \0s edited in for clarity):
array(3) {
'\0Foo\0foo' => int(1)
'\0*\0bar' => int(2)
'baz' => class stdClass#2 (0) {}
}
Output with var_export instead of var_dump:
array (
'' . "\0" . 'Foo' . "\0" . 'foo' => 1,
'' . "\0" . '*' . "\0" . 'bar' => 2,
'baz' =>
stdClass::__set_state(array(
)),
)
Typecasting this way will not do deep casting of the object graph and you need to apply the null bytes (as explained in the manual quote) to access any non-public attributes. So this works best when casting StdClass objects or objects with only public properties. For quick and dirty (what you asked for) it's fine.
Also see this in-depth blog post:
Fast PHP Object to Array conversion
You can quickly convert deeply nested objects to associative arrays by relying on the behavior of the JSON encode/decode functions:
$array = json_decode(json_encode($nested_object), true);
From the first Google hit for "PHP object to assoc array" we have this:
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;
}
The source is at codesnippets.joyent.com.
To compare it to the solution of json_decode & json_encode, this one seems faster. Here is a random benchmark (using the simple time measuring):
$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
If your object properties are public you can do:
$array = (array) $object;
If they are private or protected, they will have weird key names on the array. So, in this case you will need the following 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;
}
What about get_object_vars($obj)? It seems useful if you only want to access the public properties of an object.
See get_object_vars.
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());
Output
array(2) {
["b"]=>
string(3) "two"
["Testc"]=>
int(1)
}
array(1) {
["b"]=>
string(3) "two"
}
Type cast your object to an array.
$arr = (array) $Obj;
It will solve your problem.
Here is some code:
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;
}
All other answers posted here are only working with public attributes. Here is one solution that works with JavaBeans-like objects using reflection and getters:
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;
}
To convert an object into array just cast it explicitly:
$name_of_array = (array) $name_of_object;
You can also create a function in PHP to convert an object array:
function object_to_array($object) {
return (array) $object;
}
Use:
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;
}
It returns an array without special characters and class names.
You can easily use this function to get the result:
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;
}
Use PHP 5 or later.
Short solution of #SpYk3HH
function objectToArray($o)
{
$a = array();
foreach ($o as $k => $v)
$a[$k] = (is_array($v) || is_object($v)) ? objectToArray($v): $v;
return $a;
}
Here is my recursive PHP function to convert PHP objects to an associative array:
// ---------------------------------------------------------
// ----- 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;
}
// ---------------------------------------------------------
// ---------------------------------------------------------
Usage example:
// ---- 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);
Custom function to convert stdClass to an array:
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;
}
}
Another custom function to convert Array to 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;
}
}
Usage Example:
// 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);
First of all, if you need an array from an object you probably should constitute the data as an array first. Think about it.
Don't use a foreach statement or JSON transformations. If you're planning this, again you're working with a data structure, not with an object.
If you really need it use an object-oriented approach to have a clean and maintainable code. For example:
Object as array
class PersonArray implements \ArrayAccess, \IteratorAggregate
{
public function __construct(Person $person) {
$this->person = $person;
}
// ...
}
If you need all properties, use a transfer object:
class PersonTransferObject
{
private $person;
public function __construct(Person $person) {
$this->person = $person;
}
public function toArray() {
return [
// 'name' => $this->person->getName();
];
}
}
Also you can use The Symfony Serializer Component
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);
You might want to do this when you obtain data as objects from databases:
// 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;
}
This answer is only the union of the different answers of this post, but it's the solution to convert a PHP object with public or private properties with simple values or arrays to an associative array...
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;
}
Some impovements to the "well-knwon" code
/*** 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
Notice that if the function is member of a class (like above) you must change __FUNCTION__ to __METHOD__
For your case it was right/beautiful if you would use the "decorator" or "date model transformation" patterns. For example:
Your model
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;
}
}
Decorator
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(),
];
}
}
Usage
$car = new Car();
$car->setType('type#');
$car->setModel('model#1');
$car->setColor(255);
$carDecorator = new CarArrayDecorator($car);
$carResponseData = $carDecorator->getArray();
So it will be more beautiful and more correct code.
Converting and removing annoying stars:
$array = (array) $object;
foreach($array as $key => $val)
{
$new_array[str_replace('*_', '', $key)] = $val;
}
Probably, it will be cheaper than using reflections.
I use this (needed recursive solution with proper keys):
/**
* This method returns the array corresponding to an object, including non public members.
*
* If the deep flag is true, is will operate recursively, otherwise (if false) just at the first level.
*
* #param object $obj
* #param bool $deep = true
* #return array
* #throws \Exception
*/
public static function objectToArray(object $obj, bool $deep = true)
{
$reflectionClass = new \ReflectionClass(get_class($obj));
$array = [];
foreach ($reflectionClass->getProperties() as $property) {
$property->setAccessible(true);
$val = $property->getValue($obj);
if (true === $deep && is_object($val)) {
$val = self::objectToArray($val);
}
$array[$property->getName()] = $val;
$property->setAccessible(false);
}
return $array;
}
Example of usage, the following code:
class AA{
public $bb = null;
protected $one = 11;
}
class BB{
protected $two = 22;
}
$a = new AA();
$b = new BB();
$a->bb = $b;
var_dump($a)
Will print this:
array(2) {
["bb"] => array(1) {
["two"] => int(22)
}
["one"] => int(11)
}
There's my proposal, if you have objects in objects with even private members:
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;
}
Since a lot of people find this question because of having trouble with dynamically access attributes of an object, I will just point out that you can do this in PHP: $valueRow->{"valueName"}
In context (removed HTML output for readability):
$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 .= " ";
}
}
}
I think it is a nice idea to use traits to store object-to-array converting logic. A simple example:
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());
$Menu = new Admin_Model_DbTable_Menu();
$row = $Menu->fetchRow($Menu->select()->where('id = ?', $id));
$Addmenu = new Admin_Form_Addmenu();
$Addmenu->populate($row->toArray());
Here I've made an objectToArray() method, which also works with recursive objects, like when $objectA contains $objectB which points again to $objectA.
Additionally I've restricted the output to public properties using ReflectionClass. Get rid of it, if you don't need it.
/**
* 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;
}
To identify already used objects, I am using a protected property in this (abstract) class, named $this->usedObjects. If a recursive nested object is found, it will be replaced by the string **recursive**. Otherwise it would fail in because of infinite loop.
By using typecasting you can resolve your problem.
Just add the following lines to your return object:
$arrObj = array(yourReturnedObject);
You can also add a new key and value pair to it by using:
$arrObj['key'] = value;

Categories