合并具有相同键的两个数组

时间:2016-01-03 19:27:43

标签: php 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
);

看起来像这样:

$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
    )
    ...
);

我已尝试array_mergearray_combine,但我无法做到。我正在使用PHP 5.5$result中的密钥与$songs$sizes的密钥并不重要。我希望它不是很难。

2 个答案:

答案 0 :(得分:5)

您也可以使用array_map

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

答案 1 :(得分:1)

假设$songs$sizes的长度始终相同,

$result = array();
for($i=0;$i<count($songs);$i++) {
    $result[] = array(
        'name'=>$songs[i],
        'size'=>$sizes[i]
    );
}