0

I have two arrays that are inside foreach loop, I want to merge them to one key and value.

let the first array "array1" inside foreach:

$array1 = ['x', 'y', 'z'];

let the second array "array2" inside foreach:

$array2 = ['a', 'b', 'c'];

Expected output should be as follows:

$mergeArray = [0=>['x', 'y', 'z','a', 'b', 'c']];

What I have done is the following:

$mergeArray = [];

foreach ($customer as $key => $value) {

    $mergeArray[] = $value['items1'];
    $mergeArray[] = $value['items2'];

   echo '<pre>';     
   print_r($mergeArray);
   exit;

}

Thanks and welcome all suggestions

Bak Stak
  • 127
  • 3
  • 16
jvk
  • 2,133
  • 3
  • 19
  • 28

3 Answers3

0

Use array_merge:

$mergeArray[] = array_merge($value['item1'], $value['item2']);

Also, the exit should not be in the loop, that will prevent the loop from repeating.

Barmar
  • 741,623
  • 53
  • 500
  • 612
0

You can do it with this code

   $mergeArray = [];

  foreach ($customer as $key => $value) {

$mergeArray[0] =array_merge ( $value['items1'],  $value['items2']); 

  echo '<pre>';     
  print_r($mergeArray);
  exit; 
 }
Kvvaradha
  • 732
  • 1
  • 13
  • 28
0

Why use a foreach loop at all? Am I missing something?

$array1 = array('x', 'y', 'z');

$array2 = array('a', 'b', 'c');

$mergeArray[0] = array_merge($array1, $array2);

Output:

Array
(
    [0] => Array
        (
            [0] => x
            [1] => y
            [2] => z
            [3] => a
            [4] => b
            [5] => c
        )

)
TBowman
  • 615
  • 4
  • 15
  • You redid the question after I gave my answer. I will edit mine to do what you are now requesting. – TBowman Mar 01 '18 at 19:10
  • Why the negative rating? I answer the question clearly and have updated it according to new information provided by the OP. – TBowman Mar 01 '18 at 19:15