PHP
Transform Array to Key-Value Map with array_reduce
Discover how to effectively transform a list of associative arrays or objects into a simpler key-value map using PHP's powerful array_reduce function for efficient data restructuring.
<?php
$items = [
['product_id' => 'P001', 'name' => 'Laptop Pro', 'price' => 1500],
['product_id' => 'P002', 'name' => 'Wireless Mouse', 'price' => 50],
['product_id' => 'P003', 'name' => 'Mechanical Keyboard', 'price' => 120],
];
// Transform to an array where product_id is the key and name is the value
$productNamesMap = array_reduce($items, function($carry, $item) {
$carry[$item['product_id']] = $item['name'];
return $carry;
}, []); // Initial value for $carry is an empty array
echo "Product Names Map:
";
print_r($productNamesMap);
// Another example: Summing prices
$totalPrice = array_reduce($items, function($carry, $item) {
return $carry + $item['price'];
}, 0); // Initial value for $carry is 0
echo "
Total Price of items: " . $totalPrice . "
";
?>
How it works: This snippet demonstrates the versatility of `array_reduce` for transforming and aggregating array data. The first example iterates through a list of product associative arrays, building a new array where each product's `product_id` becomes the key and its `name` becomes the value. This is useful for creating lookup tables. The second example uses `array_reduce` to calculate the sum of all product prices, showcasing its use for simple aggregation, providing a powerful way to condense array data into a single result or a restructured array.