Array a specific column of an associative array retrieved from the database
Hello, this is Yoshino from development! In this article, I'd like to show you how to array a specific column from an associative array retrieved from DB.
Click here for table of contents
- 1. array the columns
- 2. set an arbitrary key name to the array to be retrieved
- 3. summary
Arraying Columns
When data is retrieved from DB, it is often returned in the following format.
$records = [
['id' => '1000', 'title' => 'Exercises', 'date' => '2020-04-01'],
['id' => '1001', 'title' => 'Basic Problems', 'date' => '2020-05-10'],
['id' => '1002', 'title' => 'Applied Problems', 'date' => '2020-06-20'],
];
If you want to make an array of only the title of this data, you can use the "array_column" function to get it in one line! The contents of the array are the same, but it's definitely easier to create an array from the array_column function.
// Get it with the array_column function
$titleArray = array_column($records, 'title');
print_r($titleArray);
// Output contents
Array ( [0] => Exercises [1] => Basic [2] => Applications )
// Get with foreach
$titleArray = [];
foreach($records as $record){
$titleArray[] = $record['title'];
}
print_r($titleArray);
// Output contents
Array ( [0] => Exercises [1] => Basic [2] => Applications )
Set an arbitrary key name to the array to retrieve
The array_column function has another use: array_column() returns the value of a single column, specified by column_key, in the array input. You can optionally specify an index_key. The optional index_key can be specified to return an array keyed by the value of column index_key and valued by column column_key in the input array.
// Make id the key name of the associative array
$titleArray = array_column($records, 'title', 'id');
print_r($titleArray);
// Output contents
Array ( [1000] => Exercises [1001] => Basic [1002] => Applications )
You can create an associative array with an arbitrary key name by setting the key name of $records as the third argument.
summary
In this article, I have introduced how to array a specific column of an associative array retrieved from DB.
If you use the array_column function, you can make an array in one line, so please try it.