Foreach循环不会将数据存储到嵌套数组中

时间:2019-01-23 12:28:35

标签: php arrays laravel foreach

嗨,我正在尝试将数据存储到嵌套数组中。我正在使用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"
        }
      ]
    }
  ]
}

有人可以指导我如何解决此问题并防止再次存储嵌套数组。预先感谢。

2 个答案:

答案 0 :(得分:1)

PHP将在循环的每次迭代中继续使用相同的$ nestedData变量。在继续操作之前,请在第一个循环中清除一个空的嵌套数组:

foreach($grouped_users as $r){
    $nestedData = [];

答案 1 :(得分:0)

每次在foreach之前,您都需要“删除” nestedData数组。像这样:

$nestedData['nested_data']=array()
foreach($r as $cr){