Home > Article > Backend Development > How to convert object to array in php
In PHP programming, sometimes we need to convert objects into arrays. This can be achieved through PHP built-in functions. In this article, we will briefly introduce how to convert objects to arrays in PHP.
In PHP, an object is an instance of a class. When we create an object and call methods on that object, we can use the object's properties to store and retrieve data. But sometimes we need to convert the object into an array to make it easier to manipulate the data.
In PHP, to convert an object into an array, you can use the PHP built-in functions get_object_vars()
and json_decode()
.
get_object_vars()
The function returns an associative array that contains all visible attributes of the object. This means we can convert an object into an associative array using this function.
The following is a simple example that demonstrates how to convert a PHP object to an array:
class person{ public $name = "John"; public $age = 25; public $country = "USA"; } $p = new person(); $result = get_object_vars($p); print_r($result);
The above code will output the following results:
Array ( [name] => John [age] => 25 [country] => USA )
json_decode()
The function can convert a JSON string into a PHP object or array. If we convert PHP object to JSON string and then convert JSON string to array, then we can convert PHP object to array.
Here is a simple example demonstrating how to use json_decode()
to convert a PHP object to an array:
class person{ public $name = "John"; public $age = 25; public $country = "USA"; } $p = new person(); $json = json_encode($p); $result = json_decode($json, true); print_r($result);
The above code will output the following results:
Array ( [name] => John [age] => 25 [country] => USA )
In the above example, we first convert the PHP object to a JSON string and then use json_decode()
to convert the JSON string to an array.
In PHP, converting an object to an array is an efficient way to convert object data to another data format. We can convert the object to an array using the get_object_vars()
function or the json_decode()
function. Once we convert a PHP object to an array, we can manipulate the data just like an array, which makes it easy to perform various operations.
The above is the detailed content of How to convert object to array in php. For more information, please follow other related articles on the PHP Chinese website!