【发布时间】:2019-06-17 01:07:03
【问题描述】:
您好,我正在尝试将数据存储到嵌套数组中。我正在使用 laravel,我有以下查询
$posts = User::select(DB::raw('first_name, email, left(DATE(created_at),10) as registeredDate'))
->whereHas('roles', function($q){
$q->where('name', '=', 'agent');
})
->offset(0)
->limit(5)
->orderBy('created_at','DESC')
->get();
从查询中获得结果后,我需要按registeredDate 对其分组进行排序
$grouped_users = $posts->groupBy('registeredDate');
现在我需要将结果存储到数组中,然后嵌套数组
if($grouped_users){
$index = 0;
foreach($grouped_users as $r){
$nestedData['id'] = $index;
$nestedData['counter'] = sizeof($r);
$nestedData['start_date'] = $r[0]->registeredDate;
$ChildIndex = 0;
foreach($r as $cr){
$nestedData['nested_data'][] = array(
'full_name' => $cr->first_name,
'last_login' => date('d M Y',strtotime($cr->registeredDate)),
'email' => $cr->email,
);
$ChildIndex++;
}
$data[] = $nestedData;
$index++;
}
}
上面的循环是将先前的嵌套数组数据存储到当前的嵌套数组中。
你可以看到下面我已经转换成json的例子
{
"data": [
{
"id": 0,
"counter": 3,
"start_date": "2019-01-07",
"nested_data": [
{
"full_name": "Nicolas",
"last_login": "07 Jan 2019",
"email": "aaaaa@hotmail.com"
},
{
"full_name": "michel",
"last_login": "07 Jan 2019",
"email": "bbbbbbb@orange.fr"
},
{
"full_name": "Yann",
"last_login": "07 Jan 2019",
"email": "cccccccccc@netcourrier.com"
}
]
},
{
"id": 1,
"counter": 2,
"start_date": "2019-01-05",
"nested_data": [
{
"full_name": "Nicolas",
"last_login": "07 Jan 2019",
"email": "aaaaa@hotmail.com"
},
{
"full_name": "michel",
"last_login": "07 Jan 2019",
"email": "bbbbbbb@orange.fr"
},
{
"full_name": "Yann",
"last_login": "07 Jan 2019",
"email": "cccccccccc@netcourrier.com"
},
{
"full_name": "Armin",
"last_login": "05 Jan 2019",
"email": "ggggggggggg@t-online.de"
},
{
"full_name": "Peter",
"last_login": "05 Jan 2019",
"email": "ffffff@gmx.net"
}
]
}
]
}
有人可以指导我如何解决问题并防止再次存储嵌套数组。提前致谢。
【问题讨论】:
标签: php arrays laravel foreach