P
P
po472021-06-29 11:49:41
PHP
po47, 2021-06-29 11:49:41

How to concatenate an array with the same indexes?

$a /* array (size=1)
  62 => 
    array (size=1)
      0 => int 11 //
*/

$b /* array (size=2)
  49 => 
    array (size=3)
      0 => int 1
      1 => int 2
      2 => int 3
  62 => 
    array (size=1)
      0 => int 22 //
*/

ArrayHelper::merge($a, $b) /* возвращает array (size=3)
  62 => 
    array (size=1)
      0 => int 11 //
  49 => 
    array (size=3)
      0 => int 1
      1 => int 2
      2 => int 3
  63 => 
    array (size=1)
      0 => int 22 //
*/


And you need an array in the form:
($a, $b) /* array (size=2)
  62 => 
    array (size=2)
      0 => int 11 //
      1 => int 22 //
  49 => 
    array (size=3)
      0 => int 1
      1 => int 2
      2 => int 3
  */


When using php functions ( array_merge_recursive, array_merge) indexes are overwritten by 1, 2, 3
from array_merge_recursive documentation:
If the input arrays have the same string keys, then the values ​​of those keys are merged into an array, and this is done recursively, so if one of the values ​​is an array, then the function merges it with the corresponding value in the other array. However, if the arrays have the same numeric keys, each successive value will not replace the original value, but will be added to the end of the array.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
C
colorfull, 2021-06-29
@colourfull

$a = [
62 =>[11],
102 =>[654]
];
$b = [
49 => [1,2,3],
62 => [22]
];

foreach($b as $key=>&$value){
foreach( $a as $key2=>$value2){
if($key === $key2){
$value = array_merge($value,$value2);
}
}
unset($value);
}
foreach(array_diff_key($a, $b) as $key=>$value){
$b[$key] = $value;
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question