How to convert PHP array to object: use stdClass class, use json_decode() function, use third-party library (such as ArrayObject class, Hydrator library)
PHP array Common ways to convert an object
In PHP, there are several ways to convert an array into an object. The following are some common methods:
1. Use thestdClass
class
stdClass
class is a standard class provided by PHP , can be used to create an empty object. We can use the properties of thestdClass
object to store key-value pairs in an array.
$array = ['name' => 'John Doe', 'age' => 30]; $object = new stdClass(); foreach ($array as $key => $value) { $object->$key = $value; }
2. Use the built-in functionjson_decode()
json_decode()
The function can decode the JSON string into PHP object. We can convert the array to a JSON string and then decode it into an object using thejson_decode()
function.
$array = ['name' => 'John Doe', 'age' => 30]; $json = json_encode($array); $object = json_decode($json);
3. Use third-party libraries
There are some third-party libraries that can also be used for conversion of arrays and objects, for example:
Practical case
Suppose we have a package containing Array of user data:
$users = [ ['id' => 1, 'name' => 'John Doe', 'email' => 'john@example.com'], ['id' => 2, 'name' => 'Jane Doe', 'email' => 'jane@example.com'], ];
We can convert the array to object using the above method:
UsingstdClass
Class:
foreach ($users as $user) { $object = new stdClass(); $object->id = $user['id']; $object->name = $user['name']; $object->email = $user['email']; }
Usejson_decode()
Function:
foreach ($users as $user) { $json = json_encode($user); $object = json_decode($json); }
UseArrayObject
Class:
foreach ($users as $user) { $object = new ArrayObject($user); }
Now we have a collection of objects containing user data and we can easily access their properties. For example:
echo $object->name; // 输出:"John Doe"
The above is the detailed content of What are the common ways to convert arrays to objects in PHP?. For more information, please follow other related articles on the PHP Chinese website!