简体   繁体   English

使用相同的键合并两个数组

[英]Merge two arrays with same keys

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. 我已经尝试了array_mergearray_combine但是我做不到。 I'm using PHP 5.5 . 我正在使用PHP 5.5 The keys in the $result are not important to be the same as $songs and $sizes . $result中的键与$songs$sizes相同并不重要。 I hope it's not very difficult. 我希望这不是很难。

You can also use array_map 您也可以使用array_map

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

Assuming $songs and $sizes always have the same length, 假设$songs$sizes的长度始终相同,

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM