Analysis of the Relationship between array_map and array_column in PHP

  • 2021-07-10 19:16:46
  • OfStack

In this paper, the relationship between array_map and array_column in PHP is analyzed in the form of examples. The specific analysis is as follows:

array_map () and array_column () are used as follows:

array_map (); Applies a callback function to the cells of a given array
array_column (); Quick implementation: Convert 2-D arrays to 1-D arrays

The format of the array_column () function is:

array array_column ( array $input , mixed $column_key [, mixed $index_key ] );

Returns the column in the input array with the value column_key; If the optional parameter index_key is specified, the corresponding key in the returned array is the value corresponding to the input array value index_key.

Sample code 1:


$records = array(
  array(
    'id' => 2135,
    'first_name' => 'John',
    'last_name' => 'Doe',
  ),
  array(
    'id' => 3245,
    'first_name' => 'Sally',
    'last_name' => 'Smith',
  ),
  array(
    'id' => 5342,
    'first_name' => 'Jane',
    'last_name' => 'Jones',
  ),
  array(
    'id' => 5623,
    'first_name' => 'Peter',
    'last_name' => 'Doe',
  )
);
 
$first_names = array_column($records, 'first_name');
print_r($first_names);

Output:


Array
(
  [0] => John
  [1] => Sally
  [2] => Jane
  [3] => Peter
)

Sample code 2:


$last_names = array_column($records, 'last_name', 'id');
print_r($last_names);

Output:


Array
(
  [2135] => Doe
  [3245] => Smith
  [5342] => Jones
  [5623] => Doe
)

In the absence of the array_column () function,

Implement example 1 using array_map ():


$a = array_map(function($element){    //$records Pass in the callback function as an argument 
        return $element['last_name'];        // Object that returns the value of an array element last_name Corresponding value 
}, $records);                                                  //array_map Returns an array, which is equivalent to putting each $element['last_name'] Save in a new array, so it is a new index 

Implement Example 1 with foreach:


foreach($records as $v)
{
  $b[] = $v['last_name'];
}

 Use foreach Implementation example 2 : 
$c = array();
foreach($records as $k=>$v)
{
   $c += array($v['id']=>$v['last_name']); // Use + Operator ,  In the form of an appendix ( Do not change the original array index ),  Merge assembled arrays 
}                                                     // If used array_merge The numeric key name will be renumbered 

Among the multiple pieces of data taken out, the typical 2-dimensional array can be completed by array_column () if the value of single 1 in the data corresponds to the value. However, in the face of more complex array structure, foreach can make you more flexible, but it is always preferred to use system functions first.


Related articles: