Home Backend Development PHP Tutorial How to merge multiple arrays into one array according to specified key names in PHP

How to merge multiple arrays into one array according to specified key names in PHP

Jul 07, 2023 pm 04:12 PM
Merge arrays php multidimensional array merge Merge arrays by specified key name

How to merge multiple arrays into one array according to the specified key name in PHP

In development, we often encounter the need to merge multiple arrays into one array according to the specified key name. This need is very common when working with data, especially when working with database result sets, for example. This article will introduce several common methods to achieve this function and give corresponding code examples.

Method 1: Use loop traversal

The simplest method is to use a loop to traverse all arrays and add the corresponding values ​​to the new array according to the specified key name. The sample code is as follows:

function mergeArrays($key, ...$arrays)
{
    $result = [];
    
    foreach ($arrays as $array) {
        if (isset($array[$key])) {
            $result[] = $array[$key];
        }
    }
    
    return $result;
}

$array1 = ['id' => 1, 'name' => 'Alice'];
$array2 = ['id' => 2, 'name' => 'Bob'];
$array3 = ['id' => 3, 'name' => 'Charlie'];

$result = mergeArrays('name', $array1, $array2, $array3);

print_r($result);
Copy after login

Run the above code, the output result is:

Array
(
    [0] => Alice
    [1] => Bob
    [2] => Charlie
)
Copy after login
Copy after login
Copy after login

Method 2: Use array_map function

array_map function can apply a callback function to multiple arrays on and returns a new array. We can use this function to merge multiple arrays. The sample code is as follows:

function mergeArrays($key, ...$arrays)
{
    $callback = function ($array) use ($key) {
        return $array[$key] ?? null;
    };
    
    $result = array_map($callback, $arrays);
    
    return array_filter($result, function($value) {
        return $value !== null;
    });
}

$array1 = ['id' => 1, 'name' => 'Alice'];
$array2 = ['id' => 2, 'name' => 'Bob'];
$array3 = ['id' => 3, 'name' => 'Charlie'];

$result = mergeArrays('name', $array1, $array2, $array3);

print_r($result);
Copy after login

Run the above code, the output result is:

Array
(
    [0] => Alice
    [1] => Bob
    [2] => Charlie
)
Copy after login
Copy after login
Copy after login

Method 3: Use array_reduce function

array_reduce function is used to iterate the elements in the array , process them according to the specified callback function, and return a final result. We can use this function to merge multiple arrays. The sample code is as follows:

function mergeArrays($key, ...$arrays)
{
    $callback = function ($result, $array) use ($key) {
        if (isset($array[$key])) {
            $result[] = $array[$key];
        }
        return $result;
    };
    
    $result = array_reduce($arrays, $callback, []);
    
    return $result;
}

$array1 = ['id' => 1, 'name' => 'Alice'];
$array2 = ['id' => 2, 'name' => 'Bob'];
$array3 = ['id' => 3, 'name' => 'Charlie'];

$result = mergeArrays('name', $array1, $array2, $array3);

print_r($result);
Copy after login

Run the above code, the output result is:

Array
(
    [0] => Alice
    [1] => Bob
    [2] => Charlie
)
Copy after login
Copy after login
Copy after login

The above are examples of several common methods to merge multiple arrays into one array according to the specified key name. Choosing the appropriate method according to the actual situation can greatly improve the efficiency and readability of the code. Hope this helps!

The above is the detailed content of How to merge multiple arrays into one array according to specified key names in PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to merge two arrays in C language? How to merge two arrays in C language? Sep 10, 2023 am 09:05 AM

Taking two arrays as input, try to merge or concatenate the two arrays and store the result in the third array. The logic of merging two arrays is as follows-J=0,k=0for(i=0;i<o;i++){//mergingtwoarrays if(a[j]<=b[k]){ c[i] =a[j]; j++; }else{ &nbs

Concatenate arrays using concat function in JavaScript Concatenate arrays using concat function in JavaScript Nov 18, 2023 pm 05:35 PM

In JavaScript, merging arrays is a common operation and can be achieved using the concat function. The concat function can combine multiple arrays into a new array. Let's look at a specific code example. First, we define several arrays as sample data: vararr1=[1,2,3]; vararr2=[4,5,6]; vararr3=[7,8,9]; Next, use the concat function

How to combine two-dimensional numbers in php without changing the key value How to combine two-dimensional numbers in php without changing the key value Sep 30, 2021 pm 03:09 PM

In PHP, you can use the "array_merge_recursive()" function to merge two-dimensional arrays without changing the key values; this function will not overwrite the key name when handling the situation where two or more array elements have the same key name. , instead, multiple values ​​with the same key name are recursively formed into an array.

How to merge multiple arrays into one array according to specified key names in PHP How to merge multiple arrays into one array according to specified key names in PHP Jul 07, 2023 pm 04:12 PM

How to merge multiple arrays into one array according to specified key names in PHP. During development, we often encounter the need to merge multiple arrays into one array according to specified key names. This need is very common when working with data, especially when working with database result sets, for example. This article will introduce several common methods to achieve this function and give corresponding code examples. Method 1: Use loop traversal The simplest method is to use a loop to traverse all arrays and add the corresponding values ​​​​to the new array according to the specified key name. The sample code is as follows: fu

How to merge two PHP arrays into one array How to merge two PHP arrays into one array Sep 06, 2023 am 08:52 AM

How to merge two PHP arrays into one array In PHP development, we often need to merge two arrays into one array. This operation is very common in data processing and array operations. This article will introduce how to merge two arrays simply and efficiently using PHP. PHP provides two functions to merge arrays, namely array_merge() and array_merge_recursive(). Below we introduce the usage and sample code of these two functions respectively. ar

How to merge two arrays in PHP How to merge two arrays in PHP Jul 07, 2023 am 09:57 AM

How to merge two arrays in PHP In PHP programming, you often encounter situations where you need to merge two arrays. PHP provides a variety of methods to implement array merging operations. This article will introduce several of the common methods, with code examples. Method 1: Use the array_merge function The array_merge function is a built-in function provided by PHP for merging arrays. It accepts multiple arrays as parameters and returns a merged new array. The following is the use of the array_merge function to merge two

PHP function introduction—array_combine(): Combine two arrays into an associative array PHP function introduction—array_combine(): Combine two arrays into an associative array Jul 24, 2023 am 08:33 AM

Introduction to PHP functions—array_combine(): Combine two arrays into an associative array. In PHP, there are many practical functions that can help us process and operate arrays. One very useful function is array_combine(). This article will introduce the usage of this function and its sample code. The array_combine() function uses the value of one array as the key name and the value of another array as the key value to merge the two arrays into a new associative array. this

How to merge multiple arrays in PHP How to merge multiple arrays in PHP Jul 08, 2023 pm 02:42 PM

How to merge multiple arrays in PHP In PHP, arrays are a very important data structure that are often used to store and operate multiple related data items. Sometimes, we need to merge multiple arrays into one array to process the data more conveniently. This article will explain how to merge multiple arrays in PHP and provide code examples. PHP provides a variety of methods to merge arrays. Here we will introduce three common methods: using the "+" operator, using the array_merge function and using array_m

See all articles