我有一个名为$ songs的多维数组,它输出以下内容:
Array
(
[0] => Array
(
[Michael Jackson] => Thriller
)
[1] => Array
(
[Michael Jackson] => Rock With You
)
[2] => Array
(
[Teddy Pendergrass] => Love TKO
)
[3] => Array
(
[ACDC] => Back in Black
)
)
我想合并具有重复键的数组,因此我可以得到以下内容:
Array
(
[0] => Array
(
[Michael Jackson] => Array
(
[0] => Thriller
[1] => Rock With You
)
)
[1] => Array
(
[Teddy Pendergrass] => Love TKO
)
[2] => Array
(
[ACDC] => Back in Black
)
)
我该怎么做?
为我提供输出数组的代码的奖励点如下:
<h2>Michael Jackson</h2>
<ul>
<li>Thriller</li>
<li>Thriller</li>
</ul>
<h2>Teddy Pendergrass</h2>
<ul>
<li>Love TKO</li>
</ul>
<h2>ACDC</h2>
<ul>
<li>Back in Black</li>
</ul>
答案 0 :(得分:12)
这应该这样做,它不是你想要的,但我没有看到你需要用数字索引结果数组的原因,然后是艺术家。
$source = array(
array('Michael Jackson' => 'Thriller'),
array('Michael Jackson' => 'Rock With You'),
array('Teddy Pendergrass' => 'Love TKO'),
array( 'ACDC' => 'Back in Black')
);
$result = array();
foreach($source as $item) {
$artist = key($item);
$album = current($item);
if(!isset($result[$artist])) {
$result[$artist] = array();
}
$result[$artist][] = $album;
}
您可以循环$result
数组并按照以下方式构建HTML:
foreach($result as $artist => $albums) {
echo '<h2>'.$artist.'</h2>';
echo '<ul>';
foreach($albums as $album) {
echo '<li>'.$album.'</li>';
}
echo '</ul>';
}
这将导致您描述的类似列表。