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

旧时模样 提交于 2019-12-08 11:21:38

问题


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]
);

回答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);


来源:https://stackoverflow.com/questions/49831781/how-to-merge-two-arrays-based-on-same-index-with-same-index

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!