简体   繁体   中英

how to merge two arrays in one array based on key and values pair

I have two arrays like below example..

 $arr1 = array("0" => "1");
 $arr2 = array("2" => "3");

i want to make two different array by merging all the keys in one array and and all the values inside another array.

Expected output..

$arr3 = array("0" => "2");
$arr4 = array("1" => "3");

The following work for the example given. Use array_combine with array_keys for $arr3 and reset for $arr4 -

//extract the keys and combine them
$arr3 = array_combine(array_keys($arr1), array_keys($arr2));

//extract the first value and combine them
$arr4 = array_combine(array(reset($arr1)), array(reset($arr2)));

You can do it like that, using array_keys and array_vals :

<?
    $arr1 = array("0" => "1");
    $arr2 = array("2" => "3");
    $a1_keys = array_keys($arr1);
    $a1_vals = array_values($arr1);
    $a2_keys = array_keys($arr2);
    $a2_vals = array_values($arr2);
    $keys_merge = array();
    $vals_merge = array();
    for ($i = 0; $i < count($arr1); $i++) {
        $keys_merge[$a1_keys[$i]] = $a2_keys[$i];
        $vals_merge[$a1_vals[$i]] = $a2_vals[$i];
    }
    print_r($keys_merge);
    print_r($vals_merge);

Script above assumes that You have correctly formatted arrays.

 $arr1 = array("0","1");
 $arr2 = array("2","3");

 foreach($arr1 as $key => $value){
   $arr3[$value] = $arr2[$key];
 }

That's what you need. Note: 1) your description of $arr1 and $arr2 is incorrect 2) It needs more logic when array lengths are not equal.

Perhaps you can use array_combine()

<?php
$a = array('green', 'red', 'yellow');
$b = array('avocado', 'apple', 'banana');
$c = array_combine($a, $b);

print_r($c);
?>

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