Domanda
$a = array('matches' =>
array(
'5' => array('weight' => 6),
'15' => array('weight' => 6),
)
);
$b = array('matches' =>
array(
'25' => array('weight' => 6),
'35' => array('weight' => 6),
)
);
$merge = array_merge($a, $b);
print_r($merge);
Il risultato di questo script è
Array
(
[matches] => Array
(
[25] => Array
(
[weight] => 6
)
[35] => Array
(
[weight] => 6
)
)
)
Ma perché?
Voglio che il risultato è stato questo:
Array
(
[matches] => Array
(
[5] => Array
(
[weight] => 6
)
[15] => Array
(
[weight] => 6
)
[25] => Array
(
[weight] => 6
)
[35] => Array
(
[weight] => 6
)
)
)
Soluzione
Poiché il 'matches'
chiave nel primo array viene sovrascritto con la stessa chiave nel secondo. Hai bisogno di fare questo, invece:
$merge = array('matches' => array());
$a = array(
'matches' => array(
'5' => array('weight' => 6),
'15' => array('weight' => 6)
)
);
$b = array(
'matches' => array(
'25' => array('weight' => 6),
'35' => array('weight' => 6)
)
);
$merge['matches'] = array_merge($a['matches'], $b['matches']);
print_r($merge);
Aggiorna
Al fine di preservare i tasti numerici, dovrete fare questo:
$merge['matches'] = $a['matches'] + $b['matches'];
Se si utilizza l'operatore di matrice unione come questo, basta ricordare quanto segue da php.net:
I tasti della prima matrice sarà conservata. Se una chiave matrice esiste in entrambe le matrici, quindi l'elemento dalla prima matrice sarà utilizzato e l'elemento di chiave corrispondente dalla seconda matrice verrà ignorata.
Altri suggerimenti
Prova a usare array_merge_recursive
invece di array_merge
.
Si sta fondendo il livello superiore della matrice. La funzione array_merge()
è vedere che entrambi contengono un elemento di "partite", quindi è in ripresa uno come il risultato unito.
Se si desidera che la scansione in profondità, è necessario eseguire array_merge () al livello successivo nella matrice. In questo caso è relativamente semplice, perché hai solo un elemento al livello superiore di ogni matrice, in modo da dovreste solo bisogno di una sola riga - Qualcosa di simile a questo:
$merge['matches'] = array_merge($a['matches'], $b['matches']);
Una struttura più complessa matrice avrebbe bisogno più lavoro, però.
La speranza che aiuta.
Prova:
$merge = array();
$merge['matches'] = array_merge($a['matches'], $b['matches']);
Il problema è che si uniscono al livello superiore $ un array con $ b e due di questi hanno un indice di "partite" in modo che sia accettare la versione $ di B di tale elemento. È possibile aggirare il problema mediante la fusione in modo esplicito nella matrice di indice ($ a [ 'partite'] con $ b [ 'partite']) e lo assegna alla matrice risultante dalla fusione ($ merge [ 'partite']) che si tradurrà in comportamento previsto.
In alternativa array_merge_recursive farà quello che vuoi.
Beh, si potrebbe farlo manualmente:
$mergedArray = array();
foreach($a as $key => $value)
{
$mergedArray[$key] = $value;
}
foreach($b as $key => $value)
{
$mergedArray[$key] = $value;
}