In PHP, arrays and objects are two different data types. An array is an ordered collection of data, while an object is an instance, which has its own properties and methods. However, during development, we may need to convert an array into an object. This article will introduce how to convert a PHP array into an object.
PHP Array
In PHP, arrays can come in many forms, including indexed arrays, associative arrays, and multidimensional arrays. The following is a simple associative array:
$array = [ 'name' => 'Tom', 'age' => 20, 'gender' => 'male' ];
Convert an array into an object
You can easily convert a PHP array into an object using the PHP built-in function json_decode()
. The specific steps are as follows:
json_encode()
function to convert the array into JSON format: $json = json_encode($array);
json_decode( )
The function converts JSON format into an object: $obj = json_decode($json);
At this time, $obj
is an object, and its value can be obtained by accessing the properties of the object:
echo $obj->name; // 输出:Tom echo $obj->age; // 输出:20 echo $obj->gender; // 输出:male
Therefore, we can convert PHP arrays into objects through the above steps.
Note
json_encode()
function JSON_UNESCAPED_UNICODE
to convert it Encoded as Unicode characters to avoid encoding errors. Summary
Converting a PHP array into an object is easy, just use the PHP built-in function json_decode()
. This function can create an object from a JSON-formatted string so that it has the properties of an object, including properties and methods. However, in practice, we need to pay attention to some considerations to avoid conversion errors.
The above is the detailed content of How to convert array into object in php. For more information, please follow other related articles on the PHP Chinese website!