php Method to convert a two-dimensional array to a one-dimensional array: 1. Use the array_column() function; 2. Use the array_walk() function; 3. Use the array_map() function; 4. Use the array_reduce() function; 5 , use array_walk_recursive() function.
The operating environment of this tutorial: windows7 system, PHP7.1 version, DELL G3 computer
For example, convert the following two-digit array into a one-dimensional array
$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', ] ];
1.array_column()
array_column() is PHP built-in functions, the restriction is that the PHP version must be 5.5.0 and above!
Example 1:
<?php $first_names = array_column($records, 'first_name'); var_dump($first_names); ?>
The print result is:
##Example 2:<?php $first_names = array_column($records, 'first_name','id'); var_dump($first_names); ?>
2.array_walk()
array_walk() function uses a user-defined function to Callback processing is performed on each element to implement the current function:$first_names= []; array_walk($records, function($value, $key) use (&$first_names){ $first_names[] = $value['first_name']; }); var_dump($first_names);
3.array_map()
The array_map() function is similar to array_walk(), applying the callback function to the cells of the given array.$first_names= []; array_map(function($value) use (&$first_names){ $first_names[] = $value['first_name']; }, $records); var_dump($first_names);
4.array_reduce()
array_reduce — Use a callback function to iteratively reduce an array to a single value.$first_names = array_reduce($records,function($result, $value){ array_push($result, $value['first_name']); return $result; },[]); var_dump($first_names);
5. array_walk_recursive()
array_walk_recursive — Applies the user function recursively to each member of the array. This function can convert an array of any dimension into a one-dimensional array. Recommended learning: "PHP Video Tutorial"
The above is the detailed content of How to convert two-dimensional array to one-dimensional array in php. For more information, please follow other related articles on the PHP Chinese website!