[英]Merge two array into one with the same key
我正在嘗試將具有相同鍵的兩個數組合並為一個。
在我轉儲這些變量之后
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_merge
和array_merge_recursive
但我似乎沒有工作。
我怎樣才能最好地解決這個問題?
編輯:
我的預期輸出將類似於
[
0 => [
'track' => 'Hey Brother',
'artists' => Avicii
1 => [
'track' => 'x',
'artists' => y
]
幾個選項:
$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],
];
}
您可以在回調中使用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
)
)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.