Home > database >  Add to array with the same values within loop
Add to array with the same values within loop

Time:12-02

I have a array of settings from database and I need to sort them by days. There are day start and day end periods ir each row and each day can have multiple periods so monday can have multiple records in database. results from database I have under $settings variable. This is my loop.

$items = [];
foreach($settings as $setting){
   $items[] = [
     'day' = $setting->day,
     'periods' = [
       'start' => $setting->start,
       'end' => $setting->end
      ]
   ];
}

Current result:

$items = [
  [
  'day' => 1,
  'periods' => [
    'start' => 08:00,
  'end' => 17:00
  ],
 [
  'day' => 2,
  'periods' => [
    'start' => 08:00,
  'end' => 12:00
  ],
 [
  'day' => 2,
  'periods' => [
    'start' => 14:00,
  'end' => 17:00
  ]
  
];

Desired result:

 $items = [
  [
  'day' => 1,
  'periods' => [
    'start' => 08:00,
    'end' => 17:00
   ],
 [
  'day' => 2,
  'periods' => 
    [
      'start' => 08:00,
      'end' => 12:00
    ],
    [
    'start' => 14:00,
    'end' => 17:00
    ]
  
];

CodePudding user response:

For me the best way of getting the result you want is using ->day as keys :

    foreach($settings as $setting){
        if (empty($items[$setting->day])) {
            $items[$setting->day] = [
                'day' => $setting->day,
                'periods' => [],
            ];
        }

        $items[$setting->day]['periods'][] = [
            'start' => $setting->start,
            'end' => $setting->end
            ];
    }

So you can test if the array for each day already exist (using key), if not, create it. If there is already something for this day, push a new entry in ->periods.

  •  Tags:  
  • php
  • Related