In PHP, sometimes we need to extract a column of data from a two-dimensional array for processing. In this case, we can use the PHP built-in function array_column(), which can easily extract a column from a two-dimensional array.
Syntax: array_column(array $input, mixed $column_key[, mixed $index_key])
Parameter description:
Let’s look at a practical example:
$students = array(
array('id' => 1, 'name' => 'Tom', 'score' => 80), array('id' => 2, 'name' => 'Jack', 'score' => 90), array('id' => 3, 'name' => 'Mary', 'score' => 85),
);
// Extract the grade column
$scores = array_column($students, 'score');
print_r($scores);
In the above code, we have a $students array containing information about 3 students. We use the array_column() function to extract the score column in the $students array, save it to the $scores array, and then use the print_r() function to output the value of the $scores array.
Run the above code, we can see the output:
Array
(
[0] => 80 [1] => 90 [2] => 85
)
You can see that there are only Contains the value of the score column in the $students array, but not the values of other columns.
In addition, if we want to use id as the index key in the $scores array, we can pass in the third parameter in the array_column() function:
$students = array(
array('id' => 1, 'name' => 'Tom', 'score' => 80), array('id' => 2, 'name' => 'Jack', 'score' => 90), array('id' => 3, 'name' => 'Mary', 'score' => 85),
);
// Extract the score column and use id as the index key
$scores = array_column($students, 'score', 'id');
print_r($ scores);
Output result:
Array
(
[1] => 80 [2] => 90 [3] => 85
)
We can see that the score of each element in the $scores array The key is the ID of each student in the original array, and the value is the corresponding grade.
Summary:
When dealing with two-dimensional arrays, the PHP built-in function array_column() is a very practical tool. It can easily extract the target column and avoid repeatedly writing loops to find each The cumbersome operation of key values greatly improves development efficiency.
The above is the detailed content of Get array column using PHP array_column(). For more information, please follow other related articles on the PHP Chinese website!