通过PHP(多维数组)合并非常复杂的SQL数据结果

通过PHP(多维数组)合并非常复杂的SQL数据结果,php,mysql,arrays,Php,Mysql,Arrays,对不起,我很难为这个问题写正确的线程标题。 我的问题是: 简而言之:如何合并数组项和计算 下面是完整的解释 1)我有一个(可湿性粉剂自定义)数据库来跟踪统计信息:访问量、唯一访问量等,它存储在每个日期的每篇文章中。 让它更容易理解。以下是表格的屏幕截图: 2)这是我查询时的示例数据: 所以在这个例子中,我们有多个post ID:“90”、“121”和“231” 我们在db中有多个日期:“2017-03-20”、“2017-03-21”、“2017-03-22” 我们有多种统计数据:“访问量”

对不起,我很难为这个问题写正确的线程标题。 我的问题是:

简而言之:如何合并数组项和计算

下面是完整的解释

1)我有一个(可湿性粉剂自定义)数据库来跟踪统计信息:访问量、唯一访问量等,它存储在每个日期的每篇文章中。

让它更容易理解。以下是表格的屏幕截图:

2)这是我查询时的示例数据:

所以在这个例子中,我们有多个post ID:“90”、“121”和“231”

我们在db中有多个日期:“2017-03-20”、“2017-03-21”、“2017-03-22”

我们有多种统计数据:“访问量”和“独特的访问量”

我们还为每个项目提供了一个“统计值”

每个项目都有唯一的ID

所有数据都是在事件发生时动态创建的。因此,并非所有post_id都有2个统计数据或以上日期

注意:请记住,在实际代码中,我们比上面的示例有更多的数据和变化

3)我需要合并数据:

post_id“121”与post“231”相同,因此我们需要将“stat_value”合并并添加到一个数据中,并删除“231”条目

通过PHP(动态)执行此操作的最佳方法是什么

我有以下数据:

$raw_data = array( ... ); // the one in github gist
$post_groups = array(
   '121' => array( '121', '231' ), // main post_id => array of alias.
);
它需要返回与$raw_data相同的数据格式,但删除“231”的数据,并将“231”的“stat_值”包含/求和为“121”

谢谢。

试试这个:

function david_transform_data($data, $groups) {
  if (empty($groups) === true) {
    return $data;
  }

  // Transform groups into a more useful format
  $transformed_groups = array();
  foreach ($groups as $post_id => $aliases) {
    foreach ($aliases as $alias) {
      if (absint($post_id) === absint($alias)) {
        continue;
      }

      $transformed_groups[absint($alias)] = $post_id;
    }
  }

  // Replace aliases with the real post id
  foreach ($data as $index => $stat) {
    if (isset($transformed_groups[absint($stat->post_id)]) === false) {
      continue;
    }

    $data[$index]->post_id = $transformed_groups[absint($stat->post_id)];
  }

  // Go through stats and merge those with the same post_id, stat_id
  // and stat_date
  $merged_stats = array();
  $index_tracker = 0;
  $stats_hash = array();

  foreach ($data as $index => $stat) {
    $hash_key = sprintf(
      '%s-%s-%s',
      $stat->post_id,
      $stat->stat_id,
      $stat->stat_date
    );
    if (isset($stats_hash[$hash_key]) === true) {
      $merged_stats[$stats_hash[$hash_key]]->stat_value += absint($stat->stat_value);
      continue;
    }

    $merged_stats[] = $stat;
    $stats_hash[$hash_key] = $index_tracker;
    $index_tracker++;
  }

  return $merged_stats;
}

var_dump(david_transform_data($raw_data, $post_groups));

可能会有一个更快的解决方案,但这是我想到的第一件事。

除了更改post_id,示例数据中没有您想要的更改。对吗?我还需要计算/求和/将别名post_id添加到post_id(基本上合并stat值),如果它是相同的stat_id和日期