我有一个阵列,我想重组,但我不知道这样做。
目前我的数组看起来像这样:
Array
(
[0] => Array
(
[band] => Coilguns
[date] => 2018-03-14T00:00:00Z
[location] => Jugendzentrum Epplehaus e.V.
[city] => Tubingen
[country] => Germany
)
[1] => Array
(
[band] => Coilguns
[date] => 2018-03-15T00:00:00Z
[location] => Unter Deck
[city] => Munich
[country] => Germany
)
)
我希望它看起来像:
Array
(
[0] => Array
(
[band] => Coilguns
[dates] => Array
(
[0] => Array
(
[date] => 2018-03-14T00:00:00Z
[location] => Jugendzentrum Epplehaus e.V.
[city] => Tubingen
[country] => Germany
)
[1] => Array
(
[date] => 2018-03-15T00:00:00Z
[location] => Unter Deck
[city] => Munich
[country] => Germany
)
)
)
)
基本上,我想要一个乐队数组,每个乐队的数组包含一个日期数组。是否有意义?
你应该尝试一些方法
$array = Array(
Array("band"=> "Coilguns", "date"=> "2018-03-14T00:00:00Z", "location"=> "Jugendzentrum Epplehaus e.V.", "city"=> "Tubingen", "country"=> "Germany"),
Array("band"=> "Coilguns", "date"=> "2018-03-15T00:00:00Z", "location"=> "Unter Deck", "city"=> "Munich", "country"=> "Germany"),
);
$result = Array();
$bands = array_unique(array_column($array, 'band')); //makes an array of all different "bands"
print_r($bands);
foreach($bands as $band) {
$dates = Array();
foreach($array as $row) {
if($row['band'] != $band) continue; // skip if the band is different
unset($row['band']);
$dates[] = $row;
}
$result[] = Array(
"band" => $band,
"dates" => $dates
);
}
print_r($result);
/*
Array
(
[0] => Array
(
[band] => Coilguns
[dates] => Array
(
[0] => Array
(
[date] => 2018-03-14T00:00:00Z
[location] => Jugendzentrum Epplehaus e.V.
[city] => Tubingen
[country] => Germany
)
[1] => Array
(
[date] => 2018-03-15T00:00:00Z
[location] => Unter Deck
[city] => Munich
[country] => Germany
)
)
)
)
*/
我看到你要对每个乐队名称的日期进行排序。所以我建议以下结构:
Array
(
[Coilguns] => Array
(
.. dates ..
)
)
你可以试试这段代码:
<?php
$aOriginal = array (
array ( "band"=> "Coilguns", "date"=> "2018-03-14T00:00:00Z", "location"=> "Jugendzentrum Epplehaus e.V.", "city"=> "Tubingen", "country"=> "Germany" ),
array ( "band"=> "Coilguns", "date"=> "2018-03-15T00:00:00Z", "location"=> "Unter Deck", "city"=> "Munich", "country"=> "Germany" ),
); // Your original array as stated in your post.
$aSortedArray = array ( );
foreach ( $aOriginal as $aTemp )
{
if ( ! isset ( $aSortedArray[$aTemp['band']] ) )
{
$aSortedArray[$aTemp['band']] = array ( );
}
$aSortedArray[$aTemp['band']][] = $aTemp;
}
var_dump ( $aSortedArray );
?>
这将产生:
Array
(
[Coilguns] => Array
(
[0] => Array
(
[band] => Coilguns
[date] => 2018-03-14T00:00:00Z
[location] => Jugendzentrum Epplehaus e.V.
[city] => Tubingen
[country] => Germany
)
[1] => Array
(
[band] => Coilguns
[date] => 2018-03-15T00:00:00Z
[location] => Unter Deck
[city] => Munich
[country] => Germany
)
)
)
你可以使用array_column
和array_map
:
$result = [];
array_map(function ($band, $item) use (&$result) {
$result[$band]['band'] = $band;
unset($item['band']);
$result[$band]['dates'][] = $item;
}, array_column($array, 'band'), $array);
$result = array_values($result);
这是the demo。