[英]How to merge two arrays (song&title) into one multidimensional array?
I have two arrays: 我有两个数组:
Array
(
[0] => Black
[1] => Five Hours
[2] => Bvulgari
[3] => Imaginary
)
Array
(
[0] => Pearl Jam
[1] => Deorro
[2] => Daddy's Groove
[3] => Brennan Heart
)
I want to be able to achieve the following: I want to have the song title and the Artist into one 'dimension' of the array, This is how I want it to be: 我希望能够实现以下目标:我希望将歌曲标题和歌手放在数组的一个“维度”中,这就是我想要的方式:
Array
(
[0] => Array
(
[0] => Black
[1] => Pearl Jam
)
[1] => Array
(
[0] => Five Hours
[1] => Deorro
)
[2] => Array
(
[0] => Bvulgari
[1] => Daddy's Groove
)
[3] => Array
(
[0] => Imaginary
[1] => Brennan Heart
)
)
The two arrays that are the input can change depending on the requestor's input. 输入的两个数组可以根据请求者的输入而变化。
You can use a simple foreach
loop: 您可以使用一个简单的
foreach
循环:
$songs_artists = array();
foreach ($songs as $key => $title) {
$songs_artists[] = array($title, $artists[$key]);
}
Output is as you desire. 输出是您想要的。 Demo on 3v4l.org
3v4l.org上的演示
As an alternative you could use array_map and use both array's: 或者,您可以使用array_map并使用两个数组:
$result = array_map(function ($s, $a) {
return [$s, $a];
}, $songs, $artists);
print_r($result);
Result 结果
Array
(
[0] => Array
(
[0] => Black
[1] => Pearl Jam
)
[1] => Array
(
[0] => Five Hours
[1] => Deorro
)
[2] => Array
(
[0] => Bvulgari
[1] => Daddy's Groove
)
[3] => Array
(
[0] => Imaginary
[1] => Brennan Heart
)
)
Another way to do is Array_Combine 另一种方法是Array_Combine
$songs_artists = array_combine($songs,$artists);
Array (
[Black] => Pearl Jam
[Five Hours] => Deorro
[Bvulgari] => Daddy's Groove
[Imaginary] => Brennan Heart
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.