Object properties to array php

PHP Convert object to array

Handy, I didn’t know about get_object_vars. I knew there had to be a simple way to convert a basic object to an array. Thanks!

to do this properly you need to implement a toArray() method in your class. That way you can keep your properties protected and still have access to the array of properties.
There are many ways to accomplish this, here is one method useful if you pass the object data to the constructor as an array.

//pass an array to constructor public function __construct(array $options = NULL) < //if we pass an array to the constructor if (is_array($options)) < //call setOptions() and pass the array $this->setOptions($options); > > public function setOptions(array $options) < //an array of getters and setters $methods = get_class_methods($this); //loop through the options array and call setters foreach ($options as $key =>$value) < //here we build an array of values as we set properties. $this->_data[$key] = $value; $method = 'set' . ucfirst($key); if (in_array($method, $methods)) < $this->$method($value); > > return $this; > //just return the array we built in setOptions public function toArray() < return $this->_data; > 

you can also build an array using your getters and code to make the array look how you want. Also you can use __set() and __get() to make this work as well.

when all is said and done the goal would be to have something that works like:

//instantiate an object $book = new Book(array($values); //turn object into an array $array = $book->toArray(); 

Источник

PHP Object to Array Convert using JSON Decode

The PHP object to array conversion makes it easy to access data from the object bundle. Most of the API outputs object as a response.

Some APIs may return a complex object structure. For example, a mixture of objects and arrays bundled with a response. At that time, the object to array conversion process will simplify the data parsing.

This quick example performs a PHP object to array conversion in a single step. It creates an object bundle and sets the properties.

Читайте также:  Localdatetime java разница во времени

It uses JSON encode() decode() function for the conversion. The json_decode() supplies boolean true to get the array output.

Quick example

PHP object to array conversion in a line using json_decode

id = 5678; $object->name = "William"; $object->department = "CSE"; $object->designation = "Engineer"; $result = json_encode($object); // converts object $result to array $output = json_decode($result, true); print "
"; print_r($result); ?> 

Output

After decoding, the output array is printed to the browser. The below screenshot shows the output of this program.

php object to array

Different ways of converting a PHP object to array

When converting an object to array, the object property ‘name:value’ pairs will form an associative array.

If an object contains unassigned properties then it will return an array with numerical keys.

There are two ways to achieve a PHP object to array conversion.

  1. Typecasting object into an array.
  2. Encoding and decoding object properties into an array of elements.

Typecasting is a straightforward method to convert the type of input data. The second method applies json_decode() on the given object. It supplied boolean true as a second parameter to get the output in an array format.

This article includes examples of using both of the above methods to perform the object to array conversion.

PHP object to array using typecasting

This is an alternate method to convert an object type into an array. The below program uses the same input object.

It replaces the JSON encode decode via conversion with the typecasting statement. The output will be the same as we have seen above.

The PHP typecasting syntax is shown below. It prepends the target data type enclosed with parenthesis.

$output = (target-data-type) $input 
id = 5678; $object->name = "William"; $object->department = "CSE"; $object->destination = "Engineer"; print"
"; print_r( (array) $object ); ?> 

Recursive object to array conversion

This example uses an input object with depth = 3. It adds more properties at a nested level at different depths. The hierarchical object bundle is set as the input for the conversion process.

This program defines a custom function to convert a PHP object to array. It performs the conversion recursively on each level of the input object.

id = 5678; $object->name = "William"; $object->address = new stdClass(); $object->address->email = "William@gmail.com"; $object->address->billing = new stdClass(); $object->address->billing->zipcode = 9950; $object->address->shipping = new stdClass(); $object->address->shipping->zipcode = 1234; $object->address->state = "South Carolina"; $object->address->city = "Columbia"; $object->address->country = "US"; function objectToArray($object) < foreach ($object as $k =>$obj) < if (is_object($obj)) < $object->$k = objectToArray($obj); > else < $object->$k = $obj; > > return (array) $object; > $result = objectToArray($object); print "
"; print_r($result); ?> 

This is the output of the recursive PHP object to the array conversion program above.

recursive object to array conversion

Convert PHP class object into array

This example constructs a PHP class object bundle. The class constructor sets the properties of the object during the instantiation.

Then, the Student class instance is encoded to prepare object type data. The json_encode() function prepares the JSON object to supply it for decoding. The json_decode() converts the PHP object to array.

id = $id; $this->name = $name; $this->state = $state; $this->city = $city; $this->country = $country; > > $student = new student("5678", "William", "South Carolina", "Columbia", "US"); $result = json_encode($student); $output = json_decode($result, true); print "
"; print_r($output); ?> 

Check is_object() before conversion

It is good programming practice to check the data availability before processing. This example applies the is_object verification before converting a PHP object to an array.

This method verifies if the input is an object. PHP includes exclusive functions to verify data availability and its type. Example isset(), empty(), is_array() etc.

id = $id; $this->name = $name; $this->state = $state; $this->city = $city; $this->country = $country; > > $student= new student("5678", "William", "South Carolina", "Columbia", "US"); print "
"; if (is_object($student)) < echo "Input Object:" . '
'; $result = json_encode($student); print_r($result); $studentArray = json_decode($result, true); > if(!empty($studentArray) && is_array($studentArray)) < echo "

Output Array:" . '
'; print_r($studentArray); > ?>

Convert Private, Protected object of a class

The below program defines a class with private and protected properties. The PHP code instantiates the class and creates an object bundle.

It uses both the typecasting and decoding methods to convert the object into an array.

When using typecasting, the output array index of the private property contains the class name prefix. After conversion, the array index has a * prefix for the protected properties.

name ="William"; $this->id = 5678; $this->email = "william@gmail.com"; > > print "
"; $student = new Student; $result = json_encode($student); $output1 = json_decode($result, true); print "
Using JSON decode:
"; print_r($output1); $output2 = new Student; print "

Using Type casting:
"; print_r( (array) $output2 ); ?>

This output screenshot shows the difference in the array index. Those are created from the private and protected properties of the class instance.

private protected properties

Accessing object properties with numeric keys

This code includes an associative array of student details. It also contains values with numeric keys.

When converting this array into an object, the associative array keys are used to access the object property values. There are exceptions to access properties if it doesn’t have a name.

The below code shows how to access objects with numeric keys. The key is enclosed by curly brackets to get the value.

 'William', 'email' => 'William@gmail.com', 'phone' => '12345678', 'REG5678' ); $student = (object) array( 'name' => 'William', 'email' => 'William@gmail.com', 'phone' => '12345678', 'REG5678' ); echo '
' . print_r($student, true) . '

'; echo '
' . $student->name; echo '
' . $student->email; echo '
' . $student->phone; echo '
' . $student->; ?>

Conclusion

We have seen the different ways of converting a PHP object to an array. The basic PHP typecasting has achieved an object conversion except for few special cases.

The PHP JSON encode decode process made the conversion with one line code. It accepts class objects and converts their properties into an array list.

The custom function processes recursive object to array conversion. It is to handle complex objects with mixed objects or arrays as its child elements.
download

Источник

Преобразование объекта в массив в PHP

В этой статье показано, как преобразовать объект в массив в PHP.

1. Использование приведения типов

Простым вариантом преобразования объекта в ассоциативный массив является приведение типов. Чтобы привести объект к массиву, вы можете просто указать тип массива в круглых скобках перед объектом для преобразования. Когда объект PHP преобразуется в ассоциативный массив, все свойства объекта становятся элементами массива. Например, следующее решение отбрасывает StdClass объект в массив:

Следующее решение приводит объект, имеющий только общедоступные свойства.

Как видно из приведенных выше примеров, приведение типов хорошо работает с StdClass и класс для всех общедоступных свойств. Если ваш объект содержит какие-либо закрытые поля, ключи массива будут включать область видимости. Частные и защищенные свойства будут иметь имя класса и '*' перед именем элемента соответственно. Обратите внимание, что имя класса и '*' разделены нулевым символом ( "\0" ) с обеих сторон, как показано ниже:

2. Использование get_object_vars() функция

В качестве альтернативы вы можете использовать get_object_vars() функция для получения ассоциативного массива доступных нестатических свойств указанного объекта в соответствии с областью действия. Обратите внимание, что приватные и защищенные свойства в объекте будут игнорироваться, если эта функция вызывается из области действия объекта.

3. Использование отражения

Вы можете использовать Reflection для доступа к закрытым и защищенным полям вне области действия объекта. В этом примере используется ReflectionClass::getProperties() для извлечения отраженных свойств и сохранения их в массиве. В отличие от приведения типов, это решение приводит к правильным именам ключей для непубличных полей. До PHP 8.1.0 вы должны вызывать ReflectionProperty::setAccessible() для обеспечения доступа к защищенной или частной собственности. Начиная с PHP 8.1.0 все свойства доступны по умолчанию.

Источник

Оцените статью