How to convert a two-dimensional array to an one-dimensional array by php
This article mainly explains how php converts a two-dimensional array into an one-dimensional array. Interested friends may wish to have a look at it. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn "php how to convert a two-dimensional array into an one-dimensional array".
Php two-dimensional array to one-dimensional array method: 1, with array_column () function; 2, with array_walk () function; 3, with array_map () function; 4, with array_reduce () function; 5, with array_walk_recursive () function.
Operating environment of this tutorial: windows7 system, PHP7.1 version, DELL G3 computer
Summary of two-dimensional array to one-dimensional array
For example, convert the following two-digit array to an 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 a PHP built-in function, and the restriction is that the PHP version must be 5.5.0 or above!
Example 1:
The print result is as follows:
Example 2:
The print result is as follows:
2.array_walk ()
The array_walk () function uses a user-defined function to callback each element in the array to achieve the current function:
$first_names= []; array_walk ($records, function ($value, $key) use (& $first_names) {$first_names [] = $value ['first_name'];}); var_dump ($first_names)
The print result is as follows:
3.array_map ()
The array_map () function acts similarly to array_walk (), applying the callback function to the cells of a given array.
$first_names= []; array_map (function ($value) use (& $first_names) {$first_names [] = $value ['first_name'];}, $records); var_dump ($first_names)
The print result is as follows:
4.array_reduce ()
Array_reduce-use the callback function to iteratively simplify the 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)
Print the results:
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 an one-dimensional array.
At this point, I believe you have a deeper understanding of "php how to turn a two-dimensional array into an one-dimensional array". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!