
To convert an array of objects to an associative array in PHP, you can use the array_column
function to extract the values from the objects, and then use the array_combine
function to create the associative array.
Here is an example of how you can use these functions to convert an array of objects to an associative array:
<?php
// An array of objects
$objects = [
(object) ['id' => 1, 'name' => 'Alice'],
(object) ['id' => 2, 'name' => 'Bob'],
(object) ['id' => 3, 'name' => 'Charlie'],
];
// Extract the values from the objects
$ids = array_column($objects, 'id');
$names = array_column($objects, 'name');
// Create the associative array
$associativeArray = array_combine($ids, $names);
print_r($associativeArray);
This code will output the following associative array:
Array (
[1] => Alice
[2] => Bob
[3] => Charlie
)
I hope this helps! Let me know if you have any questions or need more information.