There are two methods for converting php arrays to objects in a loop: 1. Use forced type conversion to convert the array into an object, and the keys of the array must be valid object attribute names; 2. Create a new object , and copies the elements of the array into the object, independent of whether the array keys are valid as property names of the object.
Operating system for this tutorial: Windows 10 system, php8.1.3 version, Dell G3 computer.
To loop through a PHP array into an object, you can use cast or create a new object and copy the elements of the array.
Method 1: Forced type conversion
Use forced type conversion to convert an array into an object. It is required here that the keys of the array must be valid object property names.
$array = array( 'name' => 'John', 'age' => 30, 'city' => 'New York' ); obj=(object)obj = (object) obj=(object)array; // 输出对象属性值 echo $obj->name; // 输出:John echo $obj->age; // 输出:30 echo $obj->city; // 输出:New York
Method Two: Create a new object and copy the array elements
Another method is to create a new object and copies the elements of the array into the object. This method does not rely on whether the array key is valid as an object's property name.
$array = array( 'name' => 'John', 'age' => 30, 'city' => 'New York' ); $obj = new stdClass(); foreach (arrayasarray as arrayaskey => $value) { obj−>obj->obj−>key = $value; } // 输出对象属性值 echo $obj->name; // 输出:John echo $obj->age; // 输出:30 echo $obj->city; // 输出:New York
Through the above two methods, you can convert PHP array loops into objects and easily access the object's property values.
The above is the detailed content of How to convert php array to object in loop. For more information, please follow other related articles on the PHP Chinese website!