Two methods: 1. Use the "(Object)$arr" statement to force conversion; 2. Use the "json_decode(json_encode($arr))" statement to convert the array into JSON data through json_encode, and then use json_decode converts JSON data into objects.
The operating environment of this tutorial: windows7 system, PHP8.1 version, DELL G3 computer
php will be one-dimensional Two methods to convert an array into an object
Method 1. Use the "Object" keyword to force conversion
Just add the array to the Before the variable, add the target type enclosed in brackets "(object)
"
<?php $arr=['a'=>10,'b'=>100,'c'=>'Hello']; var_dump($arr); $obj=(Object)$arr; var_dump($obj); ?>
Method 2. Use JSON data transfer
json_decode(json_encode($arr))
First use json_encode() to convert the array into JSON data
Then use json_decode() to convert the JSON data into Object
<?php $arr=['a'=>10,'b'=>100,'c'=>'Hello']; var_dump($arr); $JSON=json_encode($arr); $obj=json_decode($JSON); var_dump($JSON); var_dump($obj); ?>
Description:
json_encode() is used to JSON encode variables and will return a string, including value Representation of the value in JSON form.
json_decode() is used to decode JSON data and convert it into PHP variables
json_decode (json[,json [,json[,assoc = false [, $depth = 512 [, $options =0 ]]])
Note:
1. $json is the data to be decoded and must be utf8 encoded data;
2, $ assoc returns an array when the value is TRUE, and returns an object when FALSE;
3, $ depth is the recursion depth;
4, $option binary Mask currently only supports JSON_BIGINT_AS_STRING;
5. Generally, only the first two parameters are used. If you want data of data type, add a parameter true.
<?php $JSON='{"a":10,"b":100,"c":"Hello"}'; var_dump($JSON); $obj=json_decode($JSON); var_dump($obj); $arr=json_decode($JSON,TRUE); var_dump($arr); ?>
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of How to convert one-dimensional array to object in php. For more information, please follow other related articles on the PHP Chinese website!