PHP
Extract Multiple Columns from an Array of Associative Arrays
Transform an array of complex associative arrays into a simpler structure by extracting only a specified set of keys (columns) from each item.
function extract_columns(array $array, array $keysToExtract): array
{
$extractedData = [];
foreach ($array as $item) {
$newRow = [];
foreach ($keysToExtract as $key) {
$newRow[$key] = $item[$key] ?? null; // Use null for missing keys
}
$extractedData[] = $newRow;
}
return $extractedData;
}
$usersData = [
['id' => 1, 'name' => 'Alice', 'email' => '[email protected]', 'age' => 30],
['id' => 2, 'name' => 'Bob', 'email' => '[email protected]', 'age' => 25],
['id' => 3, 'name' => 'Charlie', 'email' => '[email protected]', 'age' => 35],
];
$desiredColumns = ['name', 'email'];
$projectedUsers = extract_columns($usersData, $desiredColumns);
/* Expected:
[
['name' => 'Alice', 'email' => '[email protected]'],
['name' => 'Bob', 'email' => '[email protected]'],
['name' => 'Charlie', 'email' => '[email protected]'],
]
*/
print_r($projectedUsers);
// Example with a missing key in the original data for one item
$usersWithMissingEmail = [
['id' => 1, 'name' => 'Alice', 'email' => '[email protected]', 'age' => 30],
['id' => 2, 'name' => 'Bob', 'age' => 25], // Email missing
];
$projectedUsersWithMissing = extract_columns($usersWithMissingEmail, ['name', 'email']);
/* Expected:
[
['name' => 'Alice', 'email' => '[email protected]'],
['name' => 'Bob', 'email' => null],
]
*/
print_r($projectedUsersWithMissing);
How it works: This function processes an array of associative arrays, extracting only the specified keys (columns) from each inner array. It iterates through the input, creating a new associative array for each item containing only the requested keys and their corresponding values. Keys not present in the original item will default to `null` in the result.