search

Home  >  Q&A  >  body text

How to conditionally merge two arrays into a two-dimensional array?

I encountered a small problem. The two arrays can be combined and written into the database quickly, but no matter how they are combined, it is not ideal. I would like to ask. Arrays 1 and 2 are composed of the same key, and the keys are changed to array1 and raary2. Can you please help, thank you

//数组1
$arry1=array
(
    [0] => 1-ASD
    [1] => 1-EWFEEF
    [2] => 1-BHRTBHTR
    [3] => 1-RTHJT
    [4] => 1-TNJRTHTR
)
//数组1
$array2=array
(
    [0] => 2-ASD
    [1] => 2-EWFEEF
    [2] => 2-BHRTBHTR
    [3] => 2-RTHJT
    [4] => 2-TNJRTHTR
)
//想要输出的二维数组形式
//1和2数组同一个key的组成一起,并且把key修改为array1和raary2
//新数组
$array=array
(
    [0] => Array
        (
            [array1] => 1-ASD
            [array2] => 2-ASD
        )
    [1] => Array
        (
            [array1] => 1-EWFEEF
            [array2] => 1-EWFEEF
        )
    [2] => Array
        (
            [array1] => 1-BHRTBHTR
            [array2] => 2-BHRTBHTR
        )
    [3] => Array
        (
            [array1] => 2-TNJRTHTR
            [array2] => 2-TNJRTHTR
        )
    [4] => Array
        (
            [array1] => 2-KMYTY
            [array2] => 2-KMYTY
        )
)


P粉925529649P粉925529649692 days ago577

reply all(1)I'll reply

  • P粉256198018

    P粉2561980182023-06-13 17:09:50

    解答

    $new_arr = [];

    foreach($array1 as $k1=>$v1){      

      foreach($arrat2 as $k2 =>$v2){         

           if($k1 == $k2){                       

                         $new_arr[$k1]['array1'] = $v1;                     $new_arr[$k1]['arrat2'] = $v2;        }    }    return $new_arr;

    }

    reply
    0
  • Cancelreply