Home >Backend Development >PHP Problem >php+ convert object to string array object array
In PHP, it is often necessary to convert some complex data into a string array or object array for easy use in different scenarios. This article will introduce some techniques on how to use PHP to convert objects into string arrays, convert string arrays into object arrays, and convert object arrays into string arrays.
In PHP, we can use the built-in function get_object_vars()
to get the attribute values of the object , and store it in an array. The code example is as follows:
class Person { public $name; public $age; public function __construct($name, $age) { $this->name = $name; $this->age = $age; } } $person = new Person('Tom', 20); $arr = get_object_vars($person); var_dump($arr);
Execute the above code, the output result is:
array(2) { ["name"]=> string(3) "Tom" ["age"]=> int(20) }
When we have a set When the string array needs to be converted into an object array, we can use the built-in function json_decode()
to achieve this. The premise is that the string array to be converted must conform to the JSON
format. The code example is as follows:
$jsonStr = '[{"name":"Tom","age":20},{"name":"Jerry","age":21}]'; $arr = json_decode($jsonStr); var_dump($arr);
The above code execution result:
array(2) { [0]=> object(stdClass)#1 (2) { ["name"]=> string(3) "Tom" ["age"]=> int(20) } [1]=> object(stdClass)#2 (2) { ["name"]=> string(5) "Jerry" ["age"]=> int(21) } }
As can be seen from the result, we successfully converted the string array into an object array.
When we need to convert object array to string array, we can use serialize()
function to achieve. It can serialize an object array into a string, and restore the serialized string to the original object array through the unserialize()
function.
The following is a sample code:
class Person { public $name; public $age; public function __construct($name, $age) { $this->name = $name; $this->age = $age; } } $persons = array(new Person('Tom', 20), new Person('Jerry', 21)); $str = serialize($persons); $arr = unserialize($str); var_dump($arr);
The above code execution result:
array(2) { [0]=> object(Person)#1 (2) { ["name"]=> string(3) "Tom" ["age"]=> int(20) } [1]=> object(Person)#2 (2) { ["name"]=> string(5) "Jerry" ["age"]=> int(21) } }
Through the above sample code, we successfully converted the object array into a string array.
This article introduces the methods of converting objects into string arrays, converting string arrays into object arrays, and converting object arrays into string arrays in PHP through three examples. Through these techniques, we can convert and process data more conveniently in PHP development.
The above is the detailed content of php+ convert object to string array object array. For more information, please follow other related articles on the PHP Chinese website!