PHP
Create Key-Value Lookup Map from Array of Associative Arrays
Transform an array of associative arrays into a flat key-value lookup map in PHP, using a specified key's value as the new array key for quick data access.
<?php
/**
* Transforms an array of associative arrays into a single associative array
* where a specified key's value becomes the new array key.
*
* @param array $array The array of associative arrays to process.
* @param string $key The key whose values will be used as the new array keys.
* @return array The resulting lookup map.
*/
function array_to_lookup_map(array $array, string $key): array
{
$lookupMap = [];
foreach ($array as $item) {
if (isset($item[$key])) {
$lookupMap[$item[$key]] = $item;
}
}
return $lookupMap;
}
// Example usage:
$users = [
['id' => 101, 'name' => 'Alice', 'role' => 'admin'],
['id' => 102, 'name' => 'Bob', 'role' => 'editor'],
['id' => 103, 'name' => 'Charlie', 'role' => 'viewer']
];
$usersById = array_to_lookup_map($users, 'id');
print_r($usersById);
/* Output:
Array
(
[101] => Array
(
[id] => 101
[name] => Alice
[role] => admin
)
[102] => Array
(
[id] => 102
[name] => Bob
[role] => editor
)
[103] => Array
(
[id] => 103
[name] => Charlie
[role] => viewer
)
)
*/
// Accessing an item directly by ID:
if (isset($usersById[102])) {
echo "User 102 name: " . $usersById[102]['name'] . "
"; // Output: User 102 name: Bob
}
// Another example, using 'name' as key (be careful with non-unique keys!)
$usersByName = array_to_lookup_map($users, 'name');
print_r($usersByName);
/* Output:
Array
(
[Alice] => Array
(
[id] => 101
[name] => Alice
[role] => admin
)
[Bob] => Array
(
[id] => 102
[name] => Bob
[role] => editor
)
[Charlie] => Array
(
[id] => 103
[name] => Charlie
[role] => viewer
)
)
*/
?>
How it works: This snippet presents a function `array_to_lookup_map` designed to convert an array of associative arrays into a new single-level associative array (a lookup map). It uses the value of a specified key from each inner associative array as the key for the new lookup map, with the entire inner array as its value. This transformation is highly beneficial for optimizing data access, allowing for direct, fast (O(1) average time complexity) retrieval of an entire record using a unique identifier, rather than iterating through the original array. It's an efficient way to make a list of records addressable by a primary key.