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:475847browse

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:

Print result:

$first_names = ['John','Sally','Jane','Peter'];

Example 2:

Print result:

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

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