Convert any two-dimensional array to one-dimensional array

content

  • 1 array_reduce function method
  • 2 array_walk_recursive function method
  • 3 array_map function method

Suppose you have the following two-dimensional array:

$user = array(
    '0' => array('id' => 100, 'username' => 'a1'), '1' => array('id' => 101, 'username' => 'a2'), '2' => array('id' => 102, 'username' => 'a3'), '3' => array('id' => 103, 'username' => 'a4'), '4' => array('id' => 104, 'username' => 'a5'), );

Now to convert to a one-dimensional array, there are two cases:

One is to convert the specified column into a one-dimensional array, which is summarized in another article: Encyclopedia of methods for PHP to extract a specified column from a multidimensional array .

Now we focus on the second case, which is to convert all values ​​into one-dimensional arrays, and the same key value will not be overwritten. The converted one-dimensional array is like this:

$result = array(100, 'a1', 101, 'a2', 102, 'a3', 103, 'a4', 104, 'a5');

There are mainly the following methods.

1 array_reduce function method

Using the array_reduce() function is a quicker way:

$result = array_reduce($user, function ($result, $value) {
    return array_merge($result, array_values($value)); }, array())

Because the array_mergefunction will overwrite and merge the arrays with the same string key name, it must be used to array_valueretrieve the value before merging.

If the second dimension is a numeric key name, such as:

$user = array(
    'a' => array(100, 'a1'), 'b' => array(101, 'a2'), 'c' => array(102, 'a3'), 'd' => array(103, 'a4'), 'e' => array(104, 'a5'), );

Then just do it like this:

$result = array_reduce($user, 'array_merge', array())

2 array_walk_recursive function method

Using the array_walk_recursive() function is very flexible and can convert an array of any dimension into a one-dimensional array.

$result = [];
array_walk_recursive($user, function($value) use (&$result) { array_push($result, $value); });

For example, the following multidimensional array:

$user4 = array(
    'a' => array(100, 'a1'), 'b' => array(101, 'a2'), 'c' => array( 'd' => array(102, 'a3'), 'e' => array(103, 'a4'), ), );

After using this method it becomes:

$result = array(100, 'a1', 101, 'a2', 102, 'a3', 103, 'a4');

3 array_map function method

array_mapSimilar to array_reducethe method of the function, as follows:

$result = [];
array_map(function ($value) use (&$result) { $result = array_merge($result, array_values($value)); }, $user);

Just need to declare an empty $resultarray.

 

In addition, the method that can also be used array_walk, and foreachthe method of looping, the principle is the same as above.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324729113&siteId=291194637