Home >Backend Development >PHP Problem >How to convert php array to obj
In PHP, arrays and objects are both used to store multiple data, but the ways of using them are still different. When we need to convert an array into an object, we can use the type conversion method that comes with PHP, or we can write our own code to implement it.
There are two main ways to convert arrays into objects in PHP:
1. Use (object) forced type conversion
In PHP, we can use (object ) casts an array type to an object type. This method is very simple, just add (object) in front of the array to convert it into an object.
The example is as follows:
$arr = array('name' => 'John', 'age' => 30); $obj = (object) $arr;
After using forced type conversion to convert the array into an object, you can use the object method to access the array elements, as follows:
echo $obj->name; // 输出:John echo $obj->age; // 输出:30
2. Manual conversion using typecasting
In addition to forced type conversion, we can also convert an array into an object by manually performing type conversion.
The example is as follows:
$arr = array('name' => 'John', 'age' => 30); $obj = new stdClass(); foreach ($arr as $key => $value) { $obj->$key = $value; }
In the above example, we first create an empty stdClass object, and then assign the key-value pair of the element to the object property by traversing the array elements. The resulting $obj object is exactly the same as the object obtained using the cast.
Summary
In PHP, converting an array into an object is very simple. We can use forced type conversion or manual type conversion to achieve it. By converting arrays into objects, we can more conveniently manipulate array elements and achieve more flexible data processing.
The above is the detailed content of How to convert php array to obj. For more information, please follow other related articles on the PHP Chinese website!