Home > Article > Backend Development > Convert php object array to key value array
In the PHP programming language, arrays are a very common data type. In object-oriented programming in PHP, we usually encounter one data type, which is an object array. An object array is a special type of array in which each element is an object. In actual development, sometimes it is necessary to convert an object array into a key-value array to facilitate related operations. This article will show you how to convert an array of objects into a key-value array using PHP.
In PHP, an object array is an array composed of multiple objects. Each object has independent properties and methods that can be used, modified, and accessed multiple times. We can create an object array through the following code:
class Person { public $name; public $age; public function __construct($name, $age) { $this->name = $name; $this->age = $age; } } $person1 = new Person("Tom", 18); $person2 = new Person("Jerry", 20); $person3 = new Person("Peter", 16); $persons = array($person1, $person2, $person3);
In the above code, we define a class named "Person" and create three objects, namely "$person1" and "$person2" ” and “$person3”. We then store them in the array variable "$persons".
In PHP, we can use "foreach" to loop through each element in an array and convert it into a key-value pair. The specific steps are as follows:
(1) Create an empty key value array:
$kv_array = array();
(2) Use foreach loop to traverse the object array, And convert the attributes of each object into key-value pairs and store them in the key-value array:
foreach($persons as $person) { $kv_array[$person->name] = $person->age; }
In the above code, we convert the "name" and "age" of each object in the object array "$persons" Attributes are converted to keys and values respectively and stored in the key-value array "$kv_array".
(3) Use the var_dump() function to view the key value array:
var_dump($kv_array);
After running the above code, we can see the following output:
array(3) { ["Tom"]=> int(18) ["Jerry"]=> int(20) ["Peter"]=> int(16) }
The above results show that, We have successfully converted an array of objects into an array of key values.
In PHP object-oriented programming, object array is a common data type. We can use foreach to loop through the object array and convert it into a key-value array to facilitate related operations. This article introduces how to use PHP to convert an object array into a key-value array, and gives specific code implementation.
The above is the detailed content of Convert php object array to key value array. For more information, please follow other related articles on the PHP Chinese website!