加入使用普通的数组值的两个多维数组 [英] Joining two multidimensional arrays using common array value

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

问题描述

我有两个数组,我想加盟为一体。两个阵列有一个共同的关键=>价值,我想给一个数组的值插入到另一个让我创建一​​个数组。

I have two arrays that I would like to join into one. Both arrays have a common key=>value and I would like to insert the values of one array to the other so that I to create one array.

阵列1


Array
(
    [0] => Array
        (
            [ID] => 123456
            [Key] => 1000
            [value] => 123.45
        )

    [1] => Array
        (
            [ID] => 789012
            [Key] => 1001
            [value] => 56748.17
        )

)

阵列2


Array
(
    [0] => Array
        (
            [Key] => 1000
            [description] => desc1
        )

    [1] => Array
        (
            [Key] => 1001
            [description] => desc2
        )

我想加盟阵列2阵列1,这样所产生的数组如下:

I would like to join Array 2 with Array 1 so that the resulting Array is as follows:



Array
(
    [0] => Array
        (
            [ID] => 123456
            [Key] => 1000
            [value] => 123.45
            [description] => desc1
        )

    [1] => Array
        (
            [ID] => 789012
            [Key] => 1001
            [value] => 56748.17
            [description] => desc2
        )

)

因此​​,阵列已使用[关键]价值的,好了,关键加入。我看着array_merge等功能,但我似乎无法得到这两个数组来合并正常。

So the arrays have been joined using the [Key] value as the, well, key. I've looked at array_merge and other function but I can't seem to get these two arrays to "merge" properly.

任何帮助将是AP preciated。

Any help would be appreciated.

推荐答案

@ radashk的解决方案将工作,如果你总是可以保证 $ ARRAY1 [$ i] 对应 $数组2 [$ i] 。从我的问题阅读,这不是保证,而是要确保 $ ARRAY1 [$ i] ['关键'] == $数组2 [$ J] ['关键'] ,并结合元素,其中,这些密钥匹配。

@radashk's solution will work if you can always guarantee that $array1[$i] corresponds to $array2[$i]. From my reading of the question, that's not guaranteed, but instead you want to make sure that $array1[$i]['Key'] == $array2[$j]['Key'], and combine elements where those Keys match.

有可能是一个更优雅的解决方案,但我会做这样的:

There may be a more elegant solution, but I would do it like this:

    // builds up new $tmpArray, using the Key as the index
$tmpArray = array();
foreach($array1 as $innerArray1){
            $tmpArray[$innerArray1['Key']] = $innerArray1;
}

    //Merges the values from $array2 into $tmpArray
foreach($array2 as $innerArray2) {
            if (isset($tmpArray[$innerArray2['Key']])) {
                $tmpArray[$innerArray2['Key']] = array_merge($tmpArray[$innerArray2['Key']], $innerArray2);
            }else{
                $tmpArray[$innerArray2['Key']] = $innerArray2;
            }

}

这篇关于加入使用普通的数组值的两个多维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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