Merge arrays and merge in php

Asked

Viewed 56 times

1

I have these 2 arrays:

$musica = [
    ["file" => "musica1"],
    ["file" => "musica2"],
    ["file" => "musica3"],
    ["file" => "musica4"],
];
$aviso = [
    ["file" => "aviso1"],
    ["file" => "aviso2"],
];

I’m trying to make a loop where every 1 song it adds 1 warning...

$resultado = array();
foreach ($musica as $mIndex => $mValue) {
    $resultado[] = $mValue;
        foreach ($aviso as $aValue) {
        if ($mIndex % 1 == 0) {
            $resultado[] = $aValue;
        }
    }
}
echo json_encode($resultado);

This way it returns the following result:

musica1
aviso1
aviso2
musica2
aviso1
aviso2
musica3
aviso1
aviso2
musica4
aviso1
aviso2

I wish it were so:

musica1
aviso1
musica2
aviso2
musica3
aviso1
musica4
aviso2
  • 2

    if ($mIndex % 1 == 0), there is some number that is not divisible by 1?

2 answers

2

Follows a solution.

$resultado = [];
$umDois = 1;
foreach ($musica as $mIndex => $mValue) {
    $resultado[] = $mValue;
    $resultado[] = 'aviso' . $umDois; 
    
    $umDois = $umDois == 1 ? 2 : 1; 
}
echo json_encode($resultado);

1


To interlink array widgets $aviso with the array elements $musica, provided that:

  • Both lists are not empty.
  • The length of $musica is greater than the length of $aviso.

Itere by array elements $musica, add to the result the current $musica and then add an array element to the result $aviso whose index is the rest of the index division of the current item in $musica for amount of elements in the array $aviso.

$musica = [
    ["file" => "musica1"],
    ["file" => "musica2"],
    ["file" => "musica3"],
    ["file" => "musica4"],
];
$aviso = [
    ["file" => "aviso1"],
    ["file" => "aviso2"],
];

$resultado = array();
foreach ($musica as $mIndex => $mValue) {
    $resultado[] = $mValue;
    $resultado[] = $aviso[$mIndex % count($aviso)];
}
echo json_encode($resultado, JSON_PRETTY_PRINT);

Upshot:

[
    {
        "file": "musica1"
    },
    {
        "file": "aviso1"
    },
    {
        "file": "musica2"
    },
    {
        "file": "aviso2"
    },
    {
        "file": "musica3"
    },
    {
        "file": "aviso1"
    },
    {
        "file": "musica4"
    },
    {
        "file": "aviso2"
    }
]

Test the code on Ideone

Browser other questions tagged

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