-1

I have a multidimensional array that looks like this:

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
  )
)

You'll notice that there are two arrays that have the same key/value pair of August and two arrays that have the same key/value pair of September. However in each case they have different keys associated with them. I'm trying to group each array on the date key where the value is the same and merge the other keys together. For example, the output would be:

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
  )
)

Any ideas?

4

1 回答 1

4

我想到的第一件事:

$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

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

于 2013-10-23T23:17:57.723 回答