PHP
Create a Lookup Map (Associative Array) from an Array of Objects
Transform a PHP array of objects or associative arrays into an efficient lookup map using a specific key as the new array's keys.
<?php
class Item {
public $sku;
public $name;
public $price;
public function __construct($sku, $name, $price) {
$this->sku = $sku;
$this->name = $name;
$this->price = $price;
}
}
$itemsList = [
new Item('SKU001', 'Widget A', 10.99),
new Item('SKU002', 'Gadget B', 24.50),
new Item('SKU003', 'Doodad C', 5.00),
];
$itemsLookup = [];
foreach ($itemsList as $item) {
$itemsLookup[$item->sku] = $item;
}
print_r($itemsLookup);
// Now you can quickly access an item by its SKU
echo "
Item with SKU002: " . $itemsLookup['SKU002']->name . "
";
// Alternative for associative arrays
$productsArr = [
['product_id' => 101, 'name' => 'Laptop', 'brand' => 'X'],
['product_id' => 102, 'name' => 'Monitor', 'brand' => 'Y'],
];
$productsMap = [];
foreach ($productsArr as $product) {
$productsMap[$product['product_id']] = $product;
}
print_r($productsMap);
?>
How it works: This snippet demonstrates how to transform a numerically indexed array of objects or associative arrays into an associative array (a lookup map). This is achieved by iterating through the original array and using a unique identifier (like an SKU or ID) from each element as the key for the new array, with the entire object/associative array as its value. This pattern allows for very fast retrieval of elements based on their identifier, avoiding linear searches.