PHP
Transform Array of Records into Key-Value Map
Efficiently convert an array of associative arrays (like database records) into a simpler key-value map in PHP, ideal for dropdowns or lookups.
<?php
$users = [
['id' => 101, 'username' => 'alice', 'email' => '[email protected]'],
['id' => 102, 'username' => 'bob', 'email' => '[email protected]'],
['id' => 103, 'username' => 'charlie', 'email' => '[email protected]']
];
// Option 1: Using array_column (simplest for direct key/value extraction)
$idToUsernameMap = array_column($users, 'username', 'id');
print_r($idToUsernameMap);
// Option 2: Custom loop for more complex transformations or checks
$emailToUserMap = [];
foreach ($users as $user) {
$emailToUserMap[$user['email']] = $user;
}
print_r($emailToUserMap);
/* Expected Output for Option 1:
Array
(
[101] => alice
[102] => bob
[103] => charlie
)
Expected Output for Option 2:
Array
(
[[email protected]] => Array
(
[id] => 101
[username] => alice
[email] => [email protected]
)
[[email protected]] => Array
(
[id] => 102
[username] => bob
[email] => [email protected]
)
[[email protected]] => Array
(
[id] => 103
[username] => charlie
[email] => [email protected]
)
)
*/
?>
How it works: This snippet shows how to transform an array of associative arrays (often results from database queries) into a simpler key-value map. The first method utilizes `array_column`, which is highly efficient for directly extracting values from one column to be the new array's values and another column's values to be the new array's keys. The second method demonstrates a `foreach` loop, providing more flexibility for complex transformations where the key or value might involve custom logic or an entire sub-array.