我有一个多维数组,如下所示:
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
)
)
您会注意到有两个阵列具有相同的八月键/值对,两个阵列具有相同的九月键值/值对。但是在每种情况下,它们都有不同的密钥。我正在尝试将每个数组分组在值相同的日期键上,并将其他键合并在一起。例如,输出将是:
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
)
)
有什么想法吗?
答案 0 :(得分:4)
首先想到的是:
$merged = array();
foreach ($array as $item)
{
$date = $item['date'];
if (!isset($merged[$date]))
{
$merged[$date] = array();
}
$merged[$date] = array_merge($merged[$date], $item);
}
结果会有一个数组,其中key是一个月。如果您想要标准索引(从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
P.S。我觉得它可以比这更好......