How to mix elements of two arrays?

Asked

Viewed 104 times

0

I wonder if there is any way to mix two arrays so that their display is alternating between the elements, I’ve tried a lot and I’m not getting. Figurative example:

I got two arrays with the exit like this:

{
   "Registros_1": [
       {
           "nome": "pedro",
           "cpf:": "00000000000",
           "sexo:": "masculino"
       },
       {
           "nome": "daniel",
           "cpf:": "11111111111",
           "sexo:": "masculino"
       }
  ]},
{
     "Registros_2": [
         {
             "nome_empresa": "JD_CARNES",
             "numero:": "00000000000",
             "usuario:": "1111"
         },
         {
             "nome_empresa": "RM_CARROS",
             "numero:": "11111111111",
             "usuario:": "2222"
         }
    ]
}

I need you to leave like this:

{
   "Registros": [
       {
           "nome": "pedro",
           "cpf:": "00000000000",
           "sexo:": "masculino"
       },
       {
           "nome_empresa": "JD_CARNES",
           "numero:": "00000000000",
           "usuario:": "1111"
       },
       {
           "nome": "daniel",
           "cpf:": "11111111111",
           "sexo:": "masculino"
       },
       {
           "nome_empresa": "RM_CARROS",
           "numero:": "11111111111",
           "usuario:": "2222"
       }

  ]

}

Thanks in advance!

  • Use the array_merge. https://www.php.net/manual/en/function.array-merge.phpfunction

  • I tried, this function joins the arrays but doesn’t let them alternate.

3 answers

1


Just implement a function for this:

function array_zip(...$arrays) {
    for ($i = 0; $i < count($arrays[0]); $i++) {
        foreach ($arrays as $array) {
            yield $array[$i];
        }
    }
}

So if you do:

$array_1 = [0, 2, 4, 6, 8];
$array_2 = [1, 3, 5, 7, 9];

foreach (array_zip($array_1, $array_2) as $n) {
    echo $n, ' ';
}

Your exit will be:

0 1 2 3 4 5 6 7 8 9

For the elements of arrays will be interpolated.

For your example, it would look something like:

$resultado = array_zip($Registros_1, $Registros_2);

Being $Registros_1 and $Registros_2 both arrays who owns.

  • With numbers worked perfectly, try to adapt somehow here

  • @Pedrosilva for your data too, just not put here because your input data are very confusing.

  • I’m having trouble adjusting!

0

Friend do not understand very well PHP but I know how to program in C, in your case I understood you would have to put some display commands within a sequence that goes up to the total value of entries made. At the time of the display you will provide the data in the desired sequence and pulling out the data of the variables.

I hope I’ve helped.

-1

Browser other questions tagged

You are not signed in. Login or sign up in order to post.