Php 按相似键/值对的多维数组组
我有一个多维数组,如下所示:Php 按相似键/值对的多维数组组,php,arrays,Php,Arrays,我有一个多维数组,如下所示: Array ( [0] => Array ( [date] => August [mozrank] => 2 [domain_authority] => 41 [external_links] => 9 [unique_visitors] => 14 ) [1] => Array ( [date] => August [post_count] =>
Array (
[0] => Array (
[date] => August
[mozrank] => 2
[domain_authority] => 41
[external_links] => 9
[unique_visitors] => 14
)
[1] => Array (
[date] => August
[post_count] => 70
[comment_count] => 53
[theme] => yes
[plugins] => 3
)
[2] => Array (
[date] => September
[mozrank] => 4
[domain_authority] => 42
[external_links] => 10
[unique_visitors] => 20
)
[3] => Array (
[date] => September
[post_count] => 71
[comment_count] => 56
[theme] => yes
[plugins] => 5
)
)
您会注意到有两个数组具有相同的键/值对August和两个数组具有相同的键/值对August。但是,在每种情况下,它们都有与之关联的不同键。我尝试将日期键上的每个数组分组,其中值相同,并将其他键合并在一起。例如,输出将是:
Array (
[0] => Array (
[date] => August
[mozrank] => 2
[domain_authority] => 41
[external_links] => 9
[unique_visitors] => 14
[post_count] => 70
[comment_count] => 53
[theme] => yes
[plugins] => 3
)
[1] => Array (
[date] => September
[mozrank] => 4
[domain_authority] => 42
[external_links] => 10
[unique_visitors] => 20
[post_count] => 71
[comment_count] => 56
[theme] => yes
[plugins] => 5
)
)
有什么想法吗?我想到的第一件事是:
$merged = array();
foreach ($array as $item)
{
$date = $item['date'];
if (!isset($merged[$date]))
{
$merged[$date] = array();
}
$merged[$date] = array_merge($merged[$date], $item);
}
因此,将有一个数组,其中键是一个月。如果您希望标准索引从0开始,则始终可以使用shuffle
结果:
array (size=2)
'August' =>
array (size=9)
'date' => string 'August' (length=6)
'mozrank' => int 2
'domain_authority' => int 41
'external_links' => int 9
'unique_visitors' => int 14
'post_count' => int 70
'comment_count' => int 53
'theme' => string 'yes' (length=3)
'plugins' => int 3
'September' =>
array (size=9)
'date' => string 'September' (length=9)
'mozrank' => int 4
'domain_authority' => int 42
'external_links' => int 10
'unique_visitors' => int 20
'post_count' => int 71
'comment_count' => int 56
'theme' => string 'yes' (length=3)
'plugins' => int 5
另外,我觉得可以做得比这更好