简体   繁体   中英

How to merge two arrays based on same index with same index

Actually i have two arrays as given below

$array1=array('0'=>'abc','1'=>'xyz');
$array2=array('0'=>'pqr','1'=>'mno');

I want to two arrays first created with key[0] and second with key[1]. means should look like as follow

$a1=array('0'=>'abc','1'=>'pqr');
$a2=array('0'=>'xyz','1'=>'mno');

The result must be

$a1 = array (
 '0' => $array1[0],
 '1' => $array2[0]
);

$a2 = array (
 '0' => $array1[1],
 '1' => $array2[1]
);

You try this code

<?php

$array1=array('0'=>'abc','1'=>'xyz');
$array2=array('0'=>'pqr','1'=>'mno');

foreach($array1 as $key => $val){
    $array_name = "a".($key + 1);
    ${$array_name} = array();
    ${$array_name}[0] = $array1[$key];
    ${$array_name}[1] = $array2[$key];
}

var_dump($a1);
var_dump($a2);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM