Home >Backend Development >PHP Problem >How to convert array to array object in php
In PHP development, arrays are one of the most common data types. In some cases, we may need to convert an ordinary array into an array object. This article will introduce how to achieve this operation.
The most common way to create array objects in PHP is to use the standard class stdClass. We can create an array object by instantiating stdClass.
$obj = new stdClass();
Next we will use the PHP function array_map(), which applies a callback function to a given array and returns A new array whose elements are the return values of each function call. This function is our key to achieving this.
The sample code is as follows:
$arr = array( array('name' => '张三', 'age' => 23), array('name' => '李四', 'age' => 29), array('name' => '王五', 'age' => 26) ); $objArr = array_map(function($item){ $obj = new stdClass(); foreach ($item as $key => $val) { $obj->$key = $val; } return $obj; }, $arr);
In the above code, we define an array that contains three sub-arrays, each sub-array contains a name and age. We use the array_map() function to convert each subarray in the original array into a new stdClass object and place the object into the new array. In the callback function, we instantiate a stdClass object, assign the key-value pair of each subarray to this new instance, and then return the instance. After calling the array_map() function, the $objArr variable obtained is an array of array objects, and each element is a stdClass object.
Once we successfully convert a normal array into an array of array objects, we can also use the array object just like a normal array. For example, we can iterate over an array object by using a foreach loop:
foreach ($objArr as $obj) { echo 'Name: ' . $obj->name . ', Age: ' . $obj->age . '<br>'; }
In the above code, we use a foreach loop to iterate through each stdClass object in the $objArr variable, and then use the object's property name to get the object attribute value. Therefore, we can access the data in the array object in the same way as a normal array.
This article describes how to convert an ordinary array in PHP into an array of array objects. We used the array_map() function to achieve this. By using the stdClass class to instantiate a new array object and assigning the key-value pairs in the original array to the new instance, we finally get an array of array objects. Such a data structure can better organize data and facilitate use in various scenarios.
The above is the detailed content of How to convert array to array object in php. For more information, please follow other related articles on the PHP Chinese website!