按相似的键/值对对进行多维数组分组


Multidimensional Array Group By Similar Key/Value Pair

我有一个多维数组,看起来像这样:

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 键/值对,两个数组具有相同的 9 月键/值对。但是,在每种情况下,它们都有与之关联的不同键。我正在尝试对值相同的日期键上的每个数组进行分组,并将其他键合并在一起。例如,输出将是:

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

附言我觉得它可以做得比这更好...