简体   繁体   English

PHP 将两个关联的 arrays 组合成一个数组

[英]PHP combine two associative arrays into one array

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

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

I need a new array combining all together, ie 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.抱歉,我忘记了,ID 永远不会相互匹配,但从技术上讲,名称可以,但不太可能,它们都需要列在一个数组中。 I looked at array_merge but wasn't sure if that was best way to do this.我查看了 array_merge 但不确定这是否是最好的方法。 Also, how would you unit test this?另外,您将如何对此进行单元测试?

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"
    }

查看array_merge()

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

There is also array_replace , where an original array is modified by other arrays preserving the key => value association 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其他阵列上的新键将在原始阵列上创建

I use a wrapper around array_merge to deal with SeanWM's comment about null arrays;我在 array_merge 周围使用了一个包装器来处理 SeanWM 关于空数组的评论; 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:这最终为:

/**
 * 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);
    }
}
        $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

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.这就是我为 PDO 查询连接两个表而提出的。 Samuel Cook is what identified a solution for me with the array_merge() +1 to him. 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.也许这会帮助其他人。

UPDATE Just a quick note, as I can see this looks really stupid, and it has no good use with pure PHP because the array_merge just works there.更新只是一个简短的说明,因为我可以看到这看起来非常愚蠢,并且它对纯 PHP 没有很好的用处,因为array_merge只是在那里工作。 BUT try it with the PHP MongoDB driver before you rush to downvote.但是,在您急于投票之前,请尝试使用 PHP MongoDB 驱动程序。 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 .使用我天真的小函数,合并完全按照传统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_replace nor array_push worked.我知道这是一个老问题,但我想再添加一个我最近使用 MongoDB 驱动程序查询遇到的案例,并且array_mergearray_replacearray_push array_replace I had a bit complex structure of objects wrapped as arrays in array:我在数组中包装为数组的对象结构有点复杂:

$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;
}

For me, this small snippet worked.对我来说,这个小片段有效。

I have similar structures for both my arrays except the keys are a little different.我的 arrays 都有类似的结构,只是键有点不同。

eg JSON 1: {"sketchCount":{"2":{"A":50477}},"raw":{"2":{"A":70477}}}例如 JSON 1: {"sketchCount":{"2":{"A":50477}},"raw":{"2":{"A":70477}}}

JSON 2: {"sketchCount":{"2":{"B":50477}},"raw":{"2":{"B":50477}}} JSON 2: {"sketchCount":{"2":{"B":50477}},"raw":{"2":{"B":50477}}}

Desired Output JSON: {"sketchCount":{"2":{"A":70477,"B":50477}},"raw":{"2":{"A":70477,"B":50477}}}所需的 Output JSON: {"sketchCount":{"2":{"A":70477,"B":50477}},"raw":{"2":{"A":70477,"B":50 }}}

Code代码

foreach($existingArray as $key => $possibleArray){
    if(is_array($possibleArray)){
      foreach($possibleArray as $index=> $value){
         $combinedArray[$key][$index] = $value;
         if(array_key_exists($key,$newArray) && array_key_exists($index,$newArray[$key])){
         foreach($newArray[$key][$index] as $newKey=> $associatedValue){
            $combinedArray[$key][$index][$newKey] = $associatedValue;
         }
         }
      }   
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM