按日期字段的Jquery或PHP组对象数组

时间:2016-06-03 11:42:13

标签: javascript php jquery mysql arrays

所以我有json响应包含为创建图表而格式化的数据(使用Canvas.js),它是一个对象数组,每个对象都包含y值(即int)和标签(这是SQL日期,如2016- 02-06)。

我需要的是按日期对这些值进行分组并从中获得平均值。数据按日期排序。问题是,一天可能有随机数点,而另一天可能根本没有任何积分。所以,我需要一种周指数(计算一年中的一周不是解决方案,因为可能有多年)。例如,我可以拥有以下数组:

[0] {y: 2; label: 2016-04-01} // this is week 1 from the start of the array
[2] {y: 6; label: 2016-04-02} // this is still week 1
[3] {y: 1; label: 2016-04-13} // this is week 2
[4] {y: 10; label: 2016-04-28} // this is week 3, if we count weeks only by appearance in the array, not by their actual position
[5] {y: 2; label: 2016-05-01} // this is week 4
[6] {y: 4; label: 2016-05-02} // still week 4

所以我需要以某种方式得到这些星期,然后找到平均y值,所以从上面的数组我会得到:

[0] {y: 4; label: 2016-04-01}
[2] {y: 1; label: 2016-04-13}
[3] {y: 10; label: 2016-04-28}
[4] {y: 3; label: 2016-05-01}

怎么办呢?我想我应该使用PHP方法并放弃尝试在前端制作它,或者可能有更简单的方法来处理它?或者也许有js图表插件允许自动分组?我非常感谢任何可能的帮助!

2 个答案:

答案 0 :(得分:1)

在Javascript中,您可以使用对象进行收集,并使用数组作为结果。

此提案使用RobGGet week of year in JavaScript like in PHP的答案。

后面的代码是一个分组部分,它采用年份和周数并收集数据进行平均计算。

// taken from https://stackoverflow.com/a/6117889/1447675
Date.prototype.getWeekNumber = function () {
    var d = new Date(+this);
    d.setHours(0, 0, 0);
    d.setDate(d.getDate() + 4 - (d.getDay() || 7));
    return Math.ceil((((d - new Date(d.getFullYear(), 0, 1)) / 8.64e7) + 1) / 7);
};

var data = [{ y: 2, label: '2016-04-01' }, { y: 6, label: '2016-04-02' }, { y: 1, label: '2016-04-13' }, { y: 10, label: '2016-04-28' }, { y: 2, label: '2016-05-01' }, { y: 4, label: '2016-05-02' }],
    avg = [];

data.forEach(function (a) {
    var year = a.label.slice(0, 4),
        week = new Date(a.label).getWeekNumber(),
        key = year + '|' + week;

    if (!this[key]) {
        this[key] = { count: 0, sum: 0, result: { y: 0, label: a.label } };
        avg.push(this[key].result);
    }
    this[key].count++;
    this[key].sum += a.y;
    this[key].result.y = this[key].sum / this[key].count;
}, Object.create(null));

console.log(avg);

答案 1 :(得分:0)

您可以尝试这样的事情:

$weeks = array();

foreach ($myData as $info) {
    $info = json_decode($info, true);
    $dateTime = new DateTime($info['label']);
    $weeksKey = $dateTime->format('W-Y');
    if (!isset($weeks[$weeksKey])) {
        $weeks[$weeksKey] = array('y' => $info['y'], 'label' => $dateTime, 'count' => 1);
    } else {
        $weeks[$weeksKey]['y'] += $info['y'];
        $weeks[$weeksKey]['count']++;
        $weeks[$weeksKey]['label'] = $weeks[$weeksKey]['label'] > $dateTime
            ? $dateTime 
            : $weeks[$weeksKey]['label'];
    }
}

$weeks = array_map(function($week) {
    return json_encode(array(
        'y' => $week['y'] / $week['count'],
        'label' => $week['label']->format('Y-m-d')
    ));
}, $weeks);

var_dump($weeks); // or var_dump(array_values($weeks));