Php custom object to array

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.

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

Источник

3 Ways – Convert a PHP Object to an Array and Vice-Versa

DISCLOSURE: This article may contain affiliate links and any sales made through such links will reward us a small commission, at no extra cost for you. Read more about Affiliate Disclosure here.

Objects and arrays are essential parts of our day to day programming. PHP object to array and array to object conversions are quite common requirements. We are mentioning three ways that you can use to convert PHP object to an array.

Vice-versa, if you’re seeking for the reverse procedure, i.e. converting an array to object then here is the link of the article. There are methods for the array to object conversion that work on a multidimensional array as well.

Convert a PHP Object to an Array

1. Typecasting Object to Array

Either object to array or array to object conversion, typecasting is the easiest solution if the input is well-structured. By well-structured means, the input has valid keys. Below is the code to typecast and convert the object to the array.

2. Convert PHP Object to Array with JSON Functions

PHP’s JSON functions can also do the object to the array or vice-versa conversion smartly. Additionally, it works perfectly with nested objects to convert them as an associative array. This is the best solution if you want a full depth recursive conversion.

First, the json_encode() function converts the object into JSON string. Further, the second parameter in json_decode() function tells PHP to convert the encoded string to an associative array.

Despite the way you use to convert PHP object to the array, also take care of a few things. For a smooth conversion, always:

  • Avoid creating StdClass object with integer properties. They become quite inaccessible even you can see them using print_r() or similar.
  • Declare objects as public members of the class. Otherwise, the array keys will have weird and dirty notations. You can check about them at the official website for PHP.

3. Object to Array Conversion using get_object_vars()

Turning an object to an array using get_object_vars() is a lesser-known yet a quite good method. Also, the popular blogging platform WordPress uses it heavily. A good example of the object to array conversion is given below:

So you see that the get_object_vars() function returns an associative array of a defined object accessible in the scope. Also, it doesn’t take non-static properties for the specified object in the account. Additionally, if a property contains no value, it will be returned with a NULL value.

Other Ways for Converting PHP Object to Array

Finally, those above are the 3 preferred ways we wanted to share to convert a PHP object to an array. Indeed, there are other ways too for the same. Object iteration through a foreach loop or using PHP’s Reflection API and recursive function calls are a few of them.

However, we haven’t discussed them here in details because personally, we don’t like long lines of code for general needs. Still, they might be useful in hacky cases. So it’s worth to provide the code for them.

Источник

Преобразование объекта в массив в 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 все свойства доступны по умолчанию.

Источник

Читайте также:  Java list minus list
Оцените статью