start_date; $end_date = $request->end_date; $lots = $request->lots; $lots = json_decode($lots, true); $begin = new \DateTime( $start_date ); $end = new \DateTime( $end_date ); $end = $end->modify( '+1 day' ); $interval = new \DateInterval('P1D'); $daterange = new \DatePeriod($begin, $interval ,$end); $dateGlobal = []; $lotsGlobal = []; foreach ($lots as $k => $lot) for ($i = 0; $i < $lot['qty']; $i++) $lotsGlobal[] = ['id' => $lot['id'], 'name' => $lot['name'], 'hour' => str_pad(mt_rand(6, 22), 2, "0", STR_PAD_LEFT) . ":" . str_pad(mt_rand(0, 59), 2, "0", STR_PAD_LEFT) . ":00"]; shuffle($lotsGlobal); foreach($daterange as $date) array_push($dateGlobal, ['date' => $date->format("Y-m-d"), 'lots' => []]); $res = $this->generate($lotsGlobal,$dateGlobal, 0); return redirect()->route('games.instantwin')->with('generated', $res); } private function generate($lotsGlobal, $dateGlobal, $lotsDone){ $rKey = array_rand($dateGlobal, 1); if ($lotsDone < count($dateGlobal)) { if (count($dateGlobal[$rKey]['lots']) > 0) { return $this->generate($lotsGlobal, $dateGlobal, $lotsDone); } } array_push($dateGlobal[$rKey]['lots'], $lotsGlobal[$lotsDone++]); if ($lotsDone < count($lotsGlobal)) { return $this->generate($lotsGlobal, $dateGlobal, $lotsDone); } foreach ($dateGlobal as $k => $date) usort($dateGlobal[$k]['lots'], [$this, 'sortFunction']); return $dateGlobal; } private function sortFunction( $a, $b ) { return strtotime($a["hour"]) - strtotime($b["hour"]); } }