The PHP code snippet demonstrates how to extract last names as keys and first names as values from a multidimensional array using the array_column function. The array, named $records, contains multiple records, each with 'id', 'first_name', and 'last_name' fields. By utilizing array_column, the code efficiently retrieves the 'first_name' values while using the corresponding 'last_name' values as keys in the resulting array.
The resulting array, named $lastNames, is printed using print_r, showcasing the last names as keys and their corresponding first names as values. This approach provides a convenient way to transform data and create a new array with the desired key-value structure based on specific fields in the original multidimensional array.
This code snippet can be useful when working with datasets where you need to extract specific fields and organize them in a key-value format for further processing or analysis.
Source code viewer
- $records = [
- ['id' => 1, 'first_name' => 'John', 'last_name' => 'Doe'],
- ['id' => 2, 'first_name' => 'Jane', 'last_name' => 'Smith'],
- ['id' => 3, 'first_name' => 'Mike', 'last_name' => 'Johnson'],
- $lastNames = array_column($records, 'last_name', 'first_name');
- // [Doe] => John
- // [Smith] => Jane
- // [Johnson] => Mike
- //)Programming Language: PHP