>我从我的数据库中有这些数据,这是给这个学生的
输出:
Array
(
[0] => stdClass Object
(
[id] => 18
[student_id] => 97
[date] => 2018-08-31
[type] => Intersexual Dormitory Visit
[amount] => 0
[count] => 3
[remark] =>
[reg_date] => 2018-09-04 16:50:16
)
[1] => stdClass Object
(
[id] => 17
[student_id] => 97
[date] => 2018-09-04
[type] => Bringing or Drinking alcohol
[amount] => 0
[count] => 1
[remark] =>
[reg_date] => 2018-09-04 16:48:54
)
[2] => stdClass Object
(
[id] => 16
[student_id] => 97
[date] => 2018-09-04
[type] => Throwing away wastes
[amount] => 0
[count] => 1
[remark] =>
[reg_date] => 2018-09-04 15:52:09
)
[3] => stdClass Object
(
[id] => 15
[student_id] => 97
[date] => 2018-09-04
[type] => Class Late
[amount] => 300
[count] => 1
[remark] => absent 1 class
[reg_date] => 2018-09-04 15:46:19
)
)
我想做的是根据date (Year and Month)
将它们分组,当amount
为0时,计为warning
,大于0时计为penalty
。
这是我的尝试:
public function getChart($in_data)
{
$this->load->model('student_model');
$student_info = $this->student_model->selectItem($in_data);
$count_warning = 0;
$count_penalty = 0;
$chart = array();
$items = parent::getItems(array('student_id'=>$student_info->member_id)); //this is for getting the Output
foreach ($items as $item) {
$count = array('penalty'=>0, 'warning'=>0);
if ($item->amount > 0) {
$count['penalty'] += $item->count;
} else {
$count['warning'] += $item->count;
}
$chart[date('Y-m', strtotime($item->date))] = $count;
}
return $chart;
}
但结果是这样的:
Array
(
[2018-08] => Array
(
[penalty] => 0
[warning] => 3
)
[2018-09] => Array
(
[penalty] => 1
[warning] => 0
)
)
问题是他在 8 月份只有 3 次警告,9 月份有 2 次警告和 1 次处罚,这将是我想要的输出,我怎么会这样?
你来了(未经测试(:
foreach ($items as $item) {
//just because I can (use array key for ease of accessing it)
$key = preg_replace('/-d{2}$/', '', $item['date']);
//you can use this instead if you want.
//$key = date('Y-m', strtotime($item->date));
//we can join our ifs tougher as the deal with the same elements
//and this will make the code more efficient
if(!isset($chart[$key])){
//add $key as month
$chart[$key] = array('penalty'=>0, 'warning'=>0, 'month'=>$key);
}else if ($item->amount > 0) {
$chart[$key]['penalty'] += $item->count;
} else {
$chart[$key]['warning'] += $item->count;
}
}
//may want to put the proper content type
//this tells the ajax call what it is and will parse it
//automatically in most browsers, so you can toss that JSON.parse().
//CAUTION:do not output data before a header call
//header('Content-type: application/json');
//array_values removes the date key, its easier to built array with it.
//then we just output the json
echo json_encode(array_values($chart));
正则表达式测试
正则表达式
-
匹配-
字面意思d
匹配任何数字- 正好
{2}
2 次 $
匹配字符串的末尾。
简而言之,它取代了2018-08-31
部分。 如果您确定日期函数始终是有效日期,请使用该函数。 如果不是,或者您不想使用日期,您可以使用正则表达式......
作为旁注,如果您使用var_export
而不是print_r
来输出数据,我会对其进行测试,因为我懒得格式化它。 有一天,我会写一些东西来为我转换它。
作为第二个旁注,我添加了标题(在注释中(,如果你的数据没有被 ajax 回调正确解析,那么你可以使用它,它应该作为一个对象出现,就像它应该的那样。 但是,一些较旧的浏览器可能会有问题,例如IE8也可能是IE9等。因为他们不理解它,所以他们可能会尝试下载 JSON 文件。 因此,这取决于您是否计划支持这些。
干杯。