这两天整一个数据,捯饬了好久。。。
需求是这样的
<?php
$a = array ();
$a[] = ['week'=>'1','day'=>'1'];
$a[] = ['week'=>'1','day'=>'2'];
$a[] = ['week'=>'1','day'=>'4'];
$a[] = ['week'=>'2','day'=>'1'];
$a[] = ['week'=>'2','day'=>'3'];
$a[] = ['week'=>'2','day'=>'5'];
// var_dump($a);
//期望输出
//$b =['1'=>'1,2,4'],['2'=>'1,3,5']
想了好多php自带的数组函数,都没有成功,后来去找大神了。
思路1:
因为数据是从数据库直接查出来的
想要的结果样式其实是可以通过SQL实现:
SELECT week,GROUP_CONCAT(`day`) as day
FROM `user_progress`
where openid ='oC_c95aBUFxnsulu6AWiS9iivtkw' && level=1
GROUP BY `week`;
结果:
这个MYSQL函数可以学习一下:GROUP_CONCAT
思路2:通过php处理实现
$a = array ();
$b = array ();
$a[] = ['week'=>'1','day'=>'1'];
$a[] = ['week'=>'1','day'=>'2'];
$a[] = ['week'=>'1','day'=>'4'];
$a[] = ['week'=>'2','day'=>'1'];
$a[] = ['week'=>'2','day'=>'3'];
$a[] = ['week'=>'2','day'=>'5'];
// var_dump($a);
foreach($a as $value){
$b[$value['week']][] = $value['day'];
}
var_dump($b);
结果
文章来源:刘俊涛的博客
欢迎关注,有问题一起学习欢迎留言、评论。