Skip to content
Advertisement

how to stop adding more data in array in foreach loop

i looping 2 array a date and the data

        $rdate = $request->month; //<-- Requested month
        $days = Carbon::create(); 
        $days = $days->daysInMonth; //<-- Finding how much days in month

        for ($i = 1; $i < $days; $i++) { //Looping Date
            $date = $rdate . '-' . $i; //Making full Date with formate 'Y-m-d'
            foreach ($games as $game) { //Looping game array have 3 collection ['game1', 'game2', 'game3']
                $result = Result::whereDate('created_at', $date)->where('game', $game->name)->where('admin_id', $admin->id)->first(); // Query Results for getting perticular game with date
                if ($result) { //Checking if current date haven't result
                    $r[] = [
                        'game' => $game->name,
                        'number' => $result->number
                    ];
                } else {
                    $r[] = [
                        'game' => $game->name,
                        'number' => '-'
                    ];
                }
            }

            $resultd[] = [
                'date' => $date,
                'results' => $r // i want to stop adding old data here
            ];
        }

i am expecting this result

{"results":[{"date":"2020-08-1","results":[{"game":"game1","number":"-"},{"game":"game2","number":"-"},{"game":"game3","number":"-"}]},{"date":"2020-08-2","results":[{"game":"game1","number":"-"},{"game":"game2","number":"-"},{"game":"game3","number":"-"}]

What actually getting

Adding old $r to results array

How to fix it i am trying to break it but can’t figure it out

Advertisement

Answer

I have some untested code, as I do not have your data but I think this code below should work, you may need to modify some code as needed.

        $rdate = '2020-8';
        
        $days = collect([1,2,3]);
        
        $games = collect(['game1', 'game2', 'game3']);
        
        return $days->map(function ($item) use ($rdate,$games) {
            $date = $rdate.'-'.$item;
            
            return [ 
             "date" => $date,
             "results" => $games->map(function ($g) use ($date) {
                 
                 $result = Result::whereDate('created_at', $date)
                                   ->where('game', $g->name)
                                   ->where('admin_id', $admin->id)
                                   ->first();
                                   
                 return ['game' => $g->name,
                         'number' => $result ? $result->number : '-',
                 ];
             })
         ];   
        });
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement