PHP 将两个关联数组合并为一个数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13170230/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 04:53:25  来源:igfitidea点击:

PHP combine two associative arrays into one array

phparraysmultidimensional-arrayassociative-array

提问by jsteinmann

$array1 = array("$name1" => "$id1");

$array2 = array("$name2" => "$id2", "$name3" => "$id3");

I need a new array combining all together, i.e. it would be

我需要一个组合在一起的新数组,即

$array3 = array("$name1" => "$id1", "$name2" => "$id2", "$name3" => "$id3");

What is the best way to do this?

做这个的最好方式是什么?

Sorry, I forgot, the ids will never match each other, but technically the names could, yet would not be likely, and they all need to be listed in one array. I looked at array_merge but wasn't sure if that was best way to do this. Also, how would you unit test this?

抱歉,我忘了,id 永远不会相互匹配,但从技术上讲,名称可以,但不太可能,并且它们都需要列在一个数组中。我查看了 array_merge,但不确定这是否是最好的方法。另外,您将如何对其进行单元测试?

回答by Samuel Cook

array_merge()is more efficient but there are a couple of options:

array_merge()效率更高,但有几种选择:

$array1 = array("id1" => "value1");

$array2 = array("id2" => "value2", "id3" => "value3", "id4" => "value4");

$array3 = array_merge($array1, $array2/*, $arrayN, $arrayN*/);
$array4 = $array1 + $array2;

echo '<pre>';
var_dump($array3);
var_dump($array4);
echo '</pre>';


// Results:
    array(4) {
      ["id1"]=>
      string(6) "value1"
      ["id2"]=>
      string(6) "value2"
      ["id3"]=>
      string(6) "value3"
      ["id4"]=>
      string(6) "value4"
    }
    array(4) {
      ["id1"]=>
      string(6) "value1"
      ["id2"]=>
      string(6) "value2"
      ["id3"]=>
      string(6) "value3"
      ["id4"]=>
      string(6) "value4"
    }

回答by Brad

Check out array_merge().

退房array_merge()

$array3 = array_merge($array1, $array2);

回答by wranvaud

There is also array_replace, where an original array is modified by other arrays preserving the key => valueassociation without creating duplicate keys.

还有array_replace,其中原始数组被其他数组修改,保留键 => 值关联而不创建重复键。

  • Same keys on other arrays will cause values to overwrite the original array
  • New keys on other arrays will be created on the original array
  • 其他数组上的相同键将导致值覆盖原始数组
  • 其他阵列上的新键将在原始阵列上创建

回答by xgretsch

I use a wrapper around array_merge to deal with SeanWM's comment about null arrays; I also sometimes want to get rid of duplicates. I'm also generally wanting to merge one array into another, as opposed to creating a new array. This ends up as:

我在 array_merge 周围使用了一个包装器来处理 SeanWM 关于空数组的评论;我有时也想摆脱重复。我通常也想将一个数组合并到另一个数组中,而不是创建一个新数组。这最终为:

/**
 * Merge two arrays - but if one is blank or not an array, return the other.
 * @param $a array First array, into which the second array will be merged
 * @param $b array Second array, with the data to be merged
 * @param $unique boolean If true, remove duplicate values before returning
 */
function arrayMerge(&$a, $b, $unique = false) {
    if (empty($b)) {
        return;  // No changes to be made to $a
    }
    if (empty($a)) {
        $a = $b;
        return;
    }
    $a = array_merge($a, $b);
    if ($unique) {
        $a = array_unique($a);
    }
}

回答by tom10271

        $array = array(
            22 => true,
            25 => true,
            34 => true,
            35 => true,
        );

        print_r(
            array_replace($array, [
                22 => true,
                42 => true,
            ])
        );

        print_r(
            array_merge($array, [
                22 => true,
                42 => true,
            ])
        );

If it is numeric but not sequential associative array, you need to use array_replace

如果是数值但不是顺序关联数组,则需要使用 array_replace

回答by lzoesch

I stumbled upon this question trying to identify a clean way to join two assoc arrays.

我偶然发现了这个问题,试图确定一种连接两个关联数组的干净方法。

I was trying to join two different tables that didn't have relationships to each other.

我试图加入两个彼此没有关系的不同表。

This is what I came up with for PDO Query joining two Tables. Samuel Cook is what identified a solution for me with the array_merge()+1 to him.

这就是我为 PDO 查询连接两个表而提出的。塞缪尔·库克 (Samuel Cook) 为我确定了一个解决方案,并array_merge()为他提供了+1。

        $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $sql = "SELECT * FROM ".databaseTbl_Residential_Prospects."";
        $ResidentialData = $pdo->prepare($sql);
        $ResidentialData->execute(array($lapi));
        $ResidentialProspects = $ResidentialData->fetchAll(PDO::FETCH_ASSOC);

        $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $sql = "SELECT * FROM ".databaseTbl_Commercial_Prospects."";
        $CommercialData = $pdo->prepare($sql);
        $CommercialData->execute(array($lapi));
        $CommercialProspects = $CommercialData->fetchAll(PDO::FETCH_ASSOC);

        $Prospects = array_merge($ResidentialProspects,$CommercialProspects);
        echo '<pre>';
        var_dump($Prospects);
        echo '</pre>';

Maybe this will help someone else out.

也许这会帮助其他人。

回答by JohnPan

UPDATEJust a quick note, as I can see this looks really stupid, and it has no good use with pure PHP because the array_mergejust works there. BUT try it with the PHP MongoDB driver before you rush to downvote. That dude WILL add indexes for whatever reason, and WILL ruin the merged object. With my na?ve little function, the merge comes out exactly the way it was supposed to with a traditional array_merge.

更新只是一个简短的说明,因为我可以看到这看起来非常愚蠢,并且它对纯 PHP 没有很好的用处,因为它array_merge只是在那里工作。但是,在您急于投票之前,请尝试使用 PHP MongoDB 驱动程序。无论出于何种原因,那个家伙都会添加索引,并且会破坏合并的对象。使用我天真的小功能,合并完全按照传统的array_merge.



I know it's an old question but I'd like to add one more case I had recently with MongoDB driver queries and none of array_merge, array_replacenor array_pushworked. I had a bit complex structure of objects wrapped as arrays in array:

我知道这是一个老问题,但我想再添加一个我最近使用 MongoDB 驱动程序查询遇到的案例,但没有一个array_mergearray_replace也没有array_push工作。我在数组中包装为数组的对象结构有点复杂:

$a = [
 ["a" => [1, "a2"]],
 ["b" => ["b1", 2]]
];
$t = [
 ["c" => ["c1", "c2"]],
 ["b" => ["b1", 2]]
];

And I needed to merge them keeping the same structure like this:

我需要合并它们,保持相同的结构,如下所示:

$merged = [
 ["a" => [1, "a2"]],
 ["b" => ["b1", 2]],
 ["c" => ["c1", "c2"]],
 ["b" => ["b1", 2]]
];

The best solution I came up with was this:

我想出的最佳解决方案是:

public static function glueArrays($arr1, $arr2) {
    // merges TWO (2) arrays without adding indexing. 
    $myArr = $arr1;
    foreach ($arr2 as $arrayItem) {
        $myArr[] = $arrayItem;
    }
    return $myArr;
}