PHP
Re-index an Array by a Specific Key's Value
Learn to transform an array of associative arrays into a new associative array where a specific key's value becomes the new top-level key for each item, allowing direct access by ID.
<?php
function reindexArrayByKey(array $array, string $key): array {
$reindexed = [];
foreach ($array as $item) {
if (isset($item[$key])) {
$reindexed[$item[$key]] = $item;
} else {
// Optionally handle items that don't have the key, e.g., skip or add to a default group
// For simplicity, this example skips them.
}
}
return $reindexed;
}
$products = [
['id' => 101, 'name' => 'Laptop', 'price' => 1200],
['id' => 102, 'name' => 'Mouse', 'price' => 25],
['id' => 103, 'name' => 'Keyboard', 'price' => 75],
];
$productsById = reindexArrayByKey($products, 'id');
print_r($productsById);
/* Output:
Array
(
[101] => Array
(
[id] => 101
[name] => Laptop
[price] => 1200
)
[102] => Array
(
[id] => 102
[name] => Mouse
[price] => 25
)
[103] => Array
(
[id] => 103
[name] => Keyboard
[price] => 75
)
)*/
// Another common way to achieve this for simple cases with unique keys:
$productsById_alternative = array_column($products, null, 'id');
print_r($productsById_alternative);
How it works: The `reindexArrayByKey` function transforms a numerically indexed array of associative arrays into an associative array where each inner array is keyed by the value of a specified field (e.g., 'id'). This creates a lookup table, allowing direct and efficient access to an item using its unique identifier, rather than iterating through the array. For example, `$productsById[101]` would directly give you the 'Laptop' details. The snippet also shows a more concise `array_column` alternative for cases where you simply want to re-index the entire item by a key.