PHP
Reorder Array Based on Key Order Map
Explore how to resequence an array of items (or associative array keys) according to a predefined order list, useful for custom sorting and display.
<?php
function reorder_array_by_keys(array $array, array $orderMap): array {
$reordered = [];
// Add elements based on the desired order
foreach ($orderMap as $key) {
if (array_key_exists($key, $array)) {
$reordered[$key] = $array[$key];
// Remove from original to easily find remaining elements later
unset($array[$key]);
}
}
// Add any remaining elements that were not in the order map
// This ensures all elements are present, even if not explicitly ordered
foreach ($array as $key => $value) {
$reordered[$key] = $value;
}
return $reordered;
}
$profileData = [
'email' => '[email protected]',
'id' => 123,
'username' => 'johndoe',
'phone' => '123-456-7890',
'address' => '123 Main St'
];
$displayOrder = ['id', 'username', 'email', 'phone', 'address'];
$orderedProfile = reorder_array_by_keys($profileData, $displayOrder);
// var_dump($orderedProfile);
/* Expected Output (simplified):
[
"id" => 123,
"username" => "johndoe",
"email" => "[email protected]",
"phone" => "123-456-7890",
"address" => "123 Main St"
]
*/
// Example for array of arrays, reordering columns (not direct array keys, but order of processing)
function reorder_array_of_arrays_columns(array $data, array $columnOrder): array {
$reorderedData = [];
foreach ($data as $row) {
$newRow = [];
foreach ($columnOrder as $colKey) {
if (array_key_exists($colKey, $row)) {
$newRow[$colKey] = $row[$colKey];
}
}
// Add any remaining columns not specified in order
foreach ($row as $colKey => $colValue) {
if (!array_key_exists($colKey, $newRow)) {
$newRow[$colKey] = $colValue;
}
}
$reorderedData[] = $newRow;
}
return $reorderedData;
}
$usersData = [
['name' => 'Alice', 'id' => 1, 'email' => '[email protected]'],
['name' => 'Bob', 'id' => 2, 'email' => '[email protected]']
];
$desiredColumnOrder = ['id', 'name', 'email'];
$orderedUsersData = reorder_array_of_arrays_columns($usersData, $desiredColumnOrder);
// var_dump($orderedUsersData);
/* Expected Output (simplified):
[
["id" => 1, "name" => "Alice", "email" => "[email protected]"],
["id" => 2, "name" => "Bob", "email" => "[email protected]"]
]
*/
?>
How it works: The `reorder_array_by_keys` function allows you to establish a custom order for the keys of an associative array. It takes the original array and an `orderMap` (an array of keys in the desired sequence). It constructs a new array by first adding elements in the specified order, then appends any remaining elements not explicitly listed in the `orderMap`. This is useful for consistent display of data where a specific field order is required. The second function demonstrates a similar concept for reordering columns in an array of arrays.