Home > OS >  Arrays: Join two arrays in one
Arrays: Join two arrays in one

Time:12-13

I have two arrays:

$array1 = 
   [
     0 =>
       [
         'data1' => value1
       ],
     1 =>
       [
          'data1' => value2
       ]
   ];



   $array2 = 
   [
     0 =>
       [
         'data2' => value1
       ],
     1 =>
       [
          'data2' => value2
       ]
   ];   

Only i want create this:

   $arrayFinish = 
   [
     0 =>
       [
         'data1' => value1,
         'data2' => value1
       ],
     1 =>
       [
          'data1' => value2
          'data2' => value2
       ]
   ];    

I have done this:

 foreach ($data1 as $key=>$val)
           {
               $arrayFinish[] =
                   [
                       $val,

                   ];

               foreach ($data2[$key] as $key2=>$val2)
               {
                  array_push($arrayFinish[$key],['data2'=>$val2]);
               }
           }

My actually result:

    array:2 [▼
         0 => array:2 [▼
            0 => {#1546 ▼
              "data1": "BWQHCLJCH"
            }
            1 => {#1547 ▼
             "data2": "00308F000825"
          }
        ]
        1 => array:2 [▼
          0 => {#1548 ▼
             "data1": "OTGSAVJIU"
           }
          1 => {#1549 ▼
             "data2": "00308F000946"
          }
         ]
        ]

I am trying to do it using PHP. I am blocked right now, i am sure that that the solution is using two loops, but i am doing any bad. If you can see my actually result is not similar to my wish result.

thank u for the help.

CodePudding user response:

Thank u to all that tried to help me. I find a solution.

I am tried to clear the array

 foreach ($array1 as $key=>$val)
           {

               $arrayFinish[$key] = $val;


               foreach ($array2[$key] as $key2=>$val2)
               {
                  array_push($arrayFinish[$key],["data2"=>$val2]);
               }
           }

Using a for cycle i can have access using one iteration to the information. This is not the great solution that i tried to find but working.

Best regards

CodePudding user response:

if your both arrays would have same no of indexes then you can do using below code

foreach ($array1 as $key=>$val) {
    $arrayFinish [] = [ $array1[$key], $array2[$key] ];
}
  • Related