The method to convert a two-dimensional array into a one-dimensional array in PHP is: you can use the array_column() function to achieve this. This function returns an array whose value is the value of a single column in the input array. The specific method is: [array_column($records, 'first_name')].
Related function introduction:
(Recommended tutorial: php tutorial)
array_column() The function returns an array whose value is the value of a single column in the input array.
Function syntax:
array_column(array,column_key,index_key);
Parameter description:
array Required. Specifies the multidimensional array (record set) to use.
column_key Required. The column whose value needs to be returned. Can be an integer index of a column of an index array, or a string key value of a column of an associative array. This parameter can also be NULL, in which case the entire array will be returned (very useful when used with the index_key parameter to reset the array key).
#index_key Optional. The column that is the index/key of the returned array.
The following array exists:
$records = [ [ 'id' => 2135, 'first_name' => 'John', 'last_name' => 'Doe', ], [ 'id' => 3245, 'first_name' => 'Sally', 'last_name' => 'Smith', ], [ 'id' => 5342, 'first_name' => 'Jane', 'last_name' => 'Jones', ], [ 'id' => 5623, 'first_name' => 'Peter', 'last_name' => 'Doe', ] ];
Code implementation:
Example 1:
<?php $first_names = array_column($records, 'first_name'); var_dump($first_names); ?>
Print result:
$first_names = ['John','Sally','Jane','Peter'];
Example 2:
<?php $first_names = array_column($records, 'first_name','id'); var_dump($first_names); ?>
Print result:
$first_names = [2135 =>'John',3245 => 'Sally',5342 => 'Jane',5623 => 'Peter'];
The above is the detailed content of How to convert a two-dimensional array to a one-dimensional array in php. For more information, please follow other related articles on the PHP Chinese website!