PHP
Convert Array of Objects to Key-Value Map using `array_reduce`
Learn to transform a PHP array of associative arrays (or objects) into a simplified key-value map using array_reduce(), dynamically selecting properties for keys and values.
<?php
$users = [
['id' => 101, 'name' => 'Alice', 'role' => 'editor'],
['id' => 102, 'name' => 'Bob', 'role' => 'admin'],
['id' => 103, 'name' => 'Charlie', 'role' => 'viewer']
];
// Convert to a map of [id => name]
$userIdToNameMap = array_reduce($users, function ($carry, $item) {
$carry[$item['id']] = $item['name'];
return $carry;
}, []);
print_r($userIdToNameMap);
// Output:
// Array
// (
// [101] => Alice
// [102] => Bob
// [103] => Charlie
// )
// Convert to a map of [role => id]
$roleToIdMap = array_reduce($users, function ($carry, $item) {
$carry[$item['role']] = $item['id'];
return $carry;
}, []);
print_r($roleToIdMap);
// Output:
// Array
// (
// [editor] => 101
// [admin] => 102
// [viewer] => 103
// )
// Handle potential duplicate keys (last one wins)
$products = [
['sku' => 'A100', 'name' => 'Widget A'],
['sku' => 'B200', 'name' => 'Gadget B'],
['sku' => 'A100', 'name' => 'New Widget A'] // Duplicate SKU
];
$skuToNameMap = array_reduce($products, function ($carry, $item) {
$carry[$item['sku']] = $item['name'];
return $carry;
}, []);
print_r($skuToNameMap);
// Output (New Widget A overwrites Widget A for A100):
// Array
// (
// [A100] => New Widget A
// [B200] => Gadget B
// )
How it works: This snippet demonstrates using `array_reduce()` to transform an array of associative arrays (or objects) into a single, flatter associative array (a key-value map). The callback function iterates through each item, taking two specified properties (e.g., `'id'` and `'name'`) from the inner associative array to form a new key-value pair in the accumulator (`$carry`). This is highly flexible for creating lookup tables or simplified data structures. If duplicate keys are generated, the last item processed will overwrite previous entries for that key.