0

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
    ]
  
];

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.