Current Location: Home> Latest Articles> How to merge values ​​of two different fields into a new array using PHP's array_column function?

How to merge values ​​of two different fields into a new array using PHP's array_column function?

M66 2025-05-11

In PHP, the array_column function is used to extract the value of a single column from a multidimensional array. It is very useful, especially if you want to extract the value of a specific field from a 2D array. So, how do you merge the values ​​of two different fields into a new array? Here is how to use array_column to implement this function.

Sample Scenario:

Suppose we have an array where each element contains the user's id and name , we want to extract these values ​​and merge them into a new array.

Code example:

 <?php
// Raw data array
$data = [
    ['id' => 1, 'name' => 'Alice'],
    ['id' => 2, 'name' => 'Bob'],
    ['id' => 3, 'name' => 'Charlie']
];

// use array_column extract 'id' and 'name'
$ids = array_column($data, 'id');
$names = array_column($data, 'name');

// Merge the values ​​of two fields
$merged = array_map(function($id, $name) {
    return ['id' => $id, 'name' => $name];
}, $ids, $names);

// Output the merged array
print_r($merged);
?>

Code explanation:

  1. Data array : We first define a two-dimensional array $data containing id and name fields.

  2. Extract data : Use the array_column function to extract the values ​​of the id and name fields from $data , and store them in the $ids and $names array.

  3. Merge array : Through the array_map function, we merge the values ​​in the $ids and $names arrays into a new associative array one by one in order, the format is ['id' => $id, 'name' => $name] .

  4. Output result : Finally, we use the print_r function to output the merged array.

Output result:

 Array
(
    [0] => Array
        (
            [id] => 1
            [name] => Alice
        )

    [1] => Array
        (
            [id] => 2
            [name] => Bob
        )

    [2] => Array
        (
            [id] => 3
            [name] => Charlie
        )
)

Summarize:

With the array_column function and array_map , we can merge different fields in the array into a new array very conveniently. The process of extracting fields by array_column is simple and fast, while array_map helps us merge the values ​​in two arrays according to the corresponding rules. This approach is not only suitable for merging two fields, but also easily extending to merging multiple fields.