Home  >  Article  >  Backend Development  >  How to convert a two-dimensional array to a one-dimensional array in php

How to convert a two-dimensional array to a one-dimensional array in php

王林
王林Original
2020-07-21 15:13:476109browse

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')].

How to convert a two-dimensional array to a one-dimensional array in php

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, &#39;first_name&#39;);
  var_dump($first_names);
?>

Print result:

$first_names = [&#39;John&#39;,&#39;Sally&#39;,&#39;Jane&#39;,&#39;Peter&#39;];

Example 2:

<?php
  $first_names = array_column($records, &#39;first_name&#39;,&#39;id&#39;);
  var_dump($first_names);
?>

Print result:

$first_names = [2135 =>&#39;John&#39;,3245 => &#39;Sally&#39;,5342 => &#39;Jane&#39;,5623 => &#39;Peter&#39;];

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn