PHP
Extracting a Column from Multidimensional PHP Arrays
Easily retrieve all values for a specific key from an array of associative arrays or objects in PHP, creating a simple indexed array using array_column() for streamlined data extraction.
<?php
$records = [
[
'id' => 2135,
'first_name' => 'John',
'last_name' => 'Doe',
],
[
'id' => 3245,
'first_name' => 'Sally',
'last_name' => 'Smith',
],
[
'id' => 5342,
'first_name' => 'Jane',
'last_name' => 'Doe',
],
[
'id' => 5623,
'first_name' => 'Peter',
'last_name' => 'Jones',
]
];
// Get a list of all first names
$firstNames = array_column($records, 'first_name');
print_r($firstNames);
// Expected output: Array ( [0] => John [1] => Sally [2] => Jane [3] => Peter )
// Get a list of IDs, using 'last_name' as the index for the new array
$indexedByIds = array_column($records, 'id', 'last_name');
print_r($indexedByIds);
/*
Expected output:
Array
(
[Doe] => 5342
[Smith] => 3245
[Jones] => 5623
)
Notice: 'Doe' has multiple entries, the last one overrides previous ones.
*/
// Example with objects
class User { public $id; public $name; public function __construct($id, $name) { $this->id = $id; $this->name = $name; } }
$users = [
new User(101, 'Alice'),
new User(102, 'Bob'),
new User(103, 'Charlie')
];
$userNames = array_column($users, 'name');
print_r($userNames);
// Expected output: Array ( [0] => Alice [1] => Bob [2] => Charlie )
?>
How it works: The `array_column()` function returns the values from a single column in the input array. It's particularly useful when dealing with arrays of associative arrays or objects, allowing you to quickly extract a specific set of values. You can also specify a `key_column` to use the values from another column as the keys in the returned array, providing a convenient way to re-index your data.