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

时间:2019-06-22 16:59:57

标签: php arrays merge m

我正在尝试将具有相同键的两个数组合并为一个。

转储这些变量后


var_dump($allArtistsName);
var_dump($allTracksName);

我得到这个输出

第一个数组

array (size=3749)
  0 => string 'Avicii' (length=6)
  1 => string 'Arctic Monkeys' (length=14)
  2 => string 'DJ Antoine' (length=10)

和第二个数组

array (size=2135)
  0 => string 'Hey Brother' (length=11)
  1 => string 'Do I Wanna Know?' (length=16)
  2 => string 'House Party - Airplay Edit' (length=26)

第一个数组中的键0基本上与第二个数组中的键0匹配。

所以我正在尝试以某种方式合并它们。

我尝试了array_mergearray_merge_recursive 但我似乎没有工作。

我该如何最好地解决这个问题?

编辑:

我的预期输出将是

[ 
  0 =>  [
       'track' => 'Hey Brother',
       'artists' => Avicii 
  1 =>  [
       'track' => 'x',
       'artists' => y
]

2 个答案:

答案 0 :(得分:3)

几个选项:

$a = ['Avicii',  'Arctic Monkeys',  'DJ Antoine'];
$t = ['Hey Brother', 'Do I Wanna Know?', 'House Party - Airplay Edit'];

// option 1 - artist name as key, track as value
print_r(array_combine($a, $t));
// option 2 - artist name  and track as subarray
print_r(array_map(null, $a, $t));
// option 3 - your expected output
$newArray = [];
foreach ($a as $key => $v) {
    $newArray[] = [
        'artist' => $v,
        'track' => $t[$key],
    ];
}

答案 1 :(得分:1)

您可以在回调中使用array_map东西:

<?php
$artists = [
    'Avicii',
    'Arctic Monkeys',
    'DJ Antoine',
];

$tracks = [
    'Hey Brother',
    'Do I Wanna Know?',
    'House Party - Airplay Edit',
];

$merged = array_map(
    function ($artist, $track) {
        return ['artist' => $artist, 'track' => $track];
    },
    $artists,
    $tracks
);

print_r($merged);

输出将是:

Array
(
    [0] => Array
        (
            [artist] => Avicii
            [track] => Hey Brother
        )

    [1] => Array
        (
            [artist] => Arctic Monkeys
            [track] => Do I Wanna Know?
        )

    [2] => Array
        (
            [artist] => DJ Antoine
            [track] => House Party - Airplay Edit
        )

)