phparraysmultidimensional-arraymappinggrouping

Use two flat arrays to populate the columns of a new 2d array


I want to merge the following arrays:

$songs = array(
    [0] => 001. Daddy's Groove Feat Mindshake - Surrender (Extended Mix).mp3
    [1] => 002. Haddaway - What Is Love (Project 46 Remix).mp3
    [2] => 003. Black Van - Fen Fires.mp3
    [3] => 004. Giorno - The Way (Radio Edit).mp3
    [4] => 005. Jack & Joy Vs Menini & Viani Ft Greg Stainer - #Aahm (Gran Hotel Mix).mp3
    [5] => 006. Almyron - Tonight (Radio Edit).mp3
    [6] => 007. Caminita Feat. Jan Peter - Tonite (Original Mix).mp3
    [7] => 008. Lucas Nord, Urban Cone, John Dahlback - We Were Gods (Original Mix).mp3
    [8] => 009. Luca Cassani - Greed (Extended Mix).mp3
    [9] => 010. Bakermat - Uitzicht.mp3
    [10] => 011. Freaky Behaviour - Dream Topping.mp3
)

$sizes = array(
    [0] => 14.1 MB
    [1] => 13.81 MB
    [2] => 12.5 MB
    [3] => 7.58 MB
    [4] => 14.15 MB
    [5] => 7.76 MB
    [6] => 10.85 MB
    [7] => 14.02 MB
    [8] => 12.66 MB
    [9] => 11.86 MB
    [10] => 17.57 MB
);

To look like this:

$result = array(
    [0] => array(
        name => 001. Daddy's Groove Feat Mindshake - Surrender (Extended Mix).mp3
        size => 14.1 MB
    )
    [1] => array(
        name => 002. Haddaway - What Is Love (Project 46 Remix).mp3
        size => 13.81 MB
    )
    ...
);

I've tried array_merge and array_combine but I couldn't do it. I'm using PHP 5.5. The keys in the $result are not important to be the same as $songs and $sizes.


Solution

  • You can also use array_map

    $result = array_map(function ($song, $size) {
        return ['song' => $song, 'size' => $size];
    }, $songs, $sizes);