Home > database >  Combine array with equal indexes PHP Arrays
Combine array with equal indexes PHP Arrays

Time:02-03

I'm trying to combine these arrays but I can't get it to work.

Array1:

array (size=6)
  1 => float 1797890.87
  2 => float 1797890.87
  3 => float 1797890.87
  4 => float 1797890.87
  6 => float 1696150.49
  5 => float 1726597.95

Array 2:

array (size=6)
  1 => float 1847326.96
  2 => float 1798634.55
  3 => float 1951034.75
  4 => float 1588295.53
  6 => float 1834365.43
  5 => float 2028421.5

This would be the desired result:

array (size=6)
  0 => 
    array (size=2)
      0 => float 1797890.87
      1 => float 1847326.96
  1 => 
    array (size=2)
      0 => float 1797890.87
      1 => float 1798634.55
  2 => 
    array (size=2)
      0 => float 1797890.87
      1 => float 1951034.75
  3 => 
    array (size=2)
      0 => float 1797890.87
      1 => float 1588295.53

  4 => 
    array (size=2)
      0 => float 1696150.49
      1 => float 1834365.43
  5 => 
    array (size=)
      0 => float 1726597.95
      1 => float 2028421.5

Try array_merge($array1, $array2) did not work. Also with array_push and the same result.

I tried with the answer of this question: HERE

But it sends an error: scalar value

CodePudding user response:

A simple loop is probably the easiest way. You use the index of the first array as an index on the second while inside the loop

$new = [];
foreach ( $array1 as $idx => $val ){
    $new[] = [$val, $array2[$idx]];
}
  •  Tags:  
  • Related