PHP combina dos matrices asociativas en una matriz


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

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

Necesito una nueva matriz que combine todos juntos, es decir, sería

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

¿Cuál es la mejor manera de hacer esto?

Lo siento, me olvidé, los ids nunca coincidirán entre sí, pero técnicamente los nombres podrían, pero no serían probables, y todos necesitan ser listados en una matriz. Miré array_merge pero no estaba seguro de si esa era la mejor manera de hacer esto. Además, ¿cómo lo probarías unitariamente?

Author: jsteinmann, 2012-11-01

7 answers

array_merge() es más eficiente, pero hay un par de opciones:

$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>';
 82
Author: Samuel Cook,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-11-01 03:05:19

Echa un vistazo array_merge().

$array3 = array_merge($array1, $array2);
 20
Author: Brad,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-11-01 02:47:31

Otra opción es array_replace , donde una matriz original es modificada por otras matrices:

  • Las mismas claves harán que los valores posteriores sobrescriban la matriz original
  • Se crearán nuevas claves en los arrays posteriores en el array original

Esto significa que la asociación key => value se conserva y no se insertan claves duplicadas.

 5
Author: wranvaud,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-03-24 14:39:04

Utilizo un wrapper alrededor de array_merge para tratar con el comentario de SeanWM sobre los arrays nulos; a veces también quiero deshacerme de los duplicados. También estoy generalmente queriendo fusionar una matriz en otra, en lugar de crear una nueva matriz. Esto termina como:

/**
 * 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);
    }
}
 2
Author: xgretsch,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-09-29 10:01:27

Me topé con esta pregunta tratando de identificar una forma limpia de unir dos arrays assoc.

Estaba tratando de unir dos tablas diferentes que no tenían relaciones entre sí.

Esto es lo que se me ocurrió para la consulta PDO que une dos tablas. Samuel Cook es lo que identificó una solución para mí con el array_merge() +1 para él.

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

Tal vez esto ayude a alguien más.

 0
Author: Kray,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-02-20 02:41:09

Sé que es una pregunta antigua, pero me gustaría agregar un caso más que tuve recientemente con las consultas del controlador MongoDB y ninguno de array_merge, array_replace nor array_push trabajado. Tenía una estructura un poco compleja de objetos envueltos como matrices en matriz:

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

Y necesitaba fusionarlos manteniendo la misma estructura como esta:

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

La mejor solución que se me ocurrió fue esta:

public static function glueArrays($arr1, $arr2) {
    // merges TWO (2) arrays without adding indexing. 
    $myArr = $arr1;
    foreach ($arr2 as $arrayItem) {
        $myArr[] = $arrayItem;
    }
    return $myArr;
}
 0
Author: JohnPan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-04-11 06:10:52
        $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,
            ])
        );

Si es una matriz asociativa numérica pero no secuencial, debe usar array_replace

 0
Author: tom10271,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-06-06 03:41:30