PHP

Extract Specific Columns from Array

Select and extract only specific columns (keys) from an array of associative arrays in PHP, creating a new array with a projected subset of data.

<?php

function extractColumns(array $array, array $columnsToExtract): array
{
    return array_map(function ($item) use ($columnsToExtract) {
        $filteredItem = [];
        foreach ($columnsToExtract as $column) {
            if (isset($item[$column])) {
                $filteredItem[$column] = $item[$column];
            }
        }
        return $filteredItem;
    }, $array);
}

$usersData = [
    ['id' => 1, 'name' => 'Alice', 'email' => '[email protected]', 'age' => 25],
    ['id' => 2, 'name' => 'Bob', 'email' => '[email protected]', 'age' => 30],
    ['id' => 3, 'name' => 'Charlie', 'email' => '[email protected]', 'age' => 35],
];

$selectedUserInfo = extractColumns($usersData, ['name', 'email']);
// print_r($selectedUserInfo);
/*
Array
(
    [0] => Array
        (
            [name] => Alice
            [email] => [email protected]
        )

    [1] => Array
        (
            [name] => Bob
            [email] => [email protected]
        )

    [2] => Array
        (
            [name] => Charlie
            [email] => [email protected]
        )

)
*/
How it works: The `extractColumns` function processes an array of associative arrays, effectively projecting specific data. It uses `array_map` to iterate over each inner array. For each inner array, it constructs a new array containing only the keys (columns) specified in `$columnsToExtract`, discarding all other keys. This is useful for creating subsets of data.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs