使用相同的键合并两个数组 [英] Merging two arrays with the same keys

查看:75
本文介绍了使用相同的键合并两个数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要合并两个数组的帮助。假设我有以下数组:

I need a help with merging two arrays. Let's say I have following arrays:

Array
(
[3] => Array
    (
        [id] => 3
        [name] => Lorem
        [type] => pl
    )

[2] => Array
    (
        [id] => 2
        [name] => Ipsum
        [type] => pl
    )

)

第二个:

Array
(
    [6] => Sit dolor
    [4] => nostrud exercitation ullamco
    [3] => uuntur magni dolores
    [2] => corporis suscipit laboriosam
    [7] =>  quia non numquam eius modi tempora
 )

所需的输出为:

Array
(
[3] => Array
    (
        [id] => 3
        [name] => Lorem
        [type] => pl
        [new_key] => uuntur magni dolores
    )

[2] => Array
    (
        [id] => 2
        [name] => Ipsum
        [type] => pl
        [new_key] => corporis suscipit laboriosam
    )
)

我一直在尝试将数组与 array_diff_key()方法,然后在某些循环中合并数组,但是我无法使其工作。有内置的PHP函数,还是我应该编写自己的函数?如果是这样,您能帮助我取得理想的结果吗?

I have been trying to compare arrays with array_diff_key() method and than merge arrays in some loop, but I could't get it working. Is there any built in PHP function, or should I write my own? If so, could you help me with getting desired result? Any help is much appreciated.

推荐答案

您可以简单地遍历第一个数组:

You can simply iterate over first array:

foreach ($arr1 as $key=> $item) {
    $arr1[$key]['new_key'] = isset($arr2[$item['id']]) ? $arr2[$item['id']] : '';
}

foreach ($arr1 as &$item) { //just for fun
    $item['new_key'] = isset($arr2[$item['id']]) ? $arr2[$item['id']] : '';
}

但是您的数据似乎来自数据库。如果我是对的,则最好使用sql JOIN

But it seems that your data comes from database. If I am right, you'd better use sql JOIN.

这篇关于使用相同的键合并两个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆