V
V
Vanik Khachatryan2018-03-31 02:33:54
PHP
Vanik Khachatryan, 2018-03-31 02:33:54

Why is looping with data from a database in Laravel not working correctly?

Here is the controller:

$tickets = Ticket::where('slot_id', $slot_id)->get();
        $ar = [];
        $slots = Slot::find($slot_id);

        $i = 2;
        do {
            foreach (json_decode($tickets) as $ticket) {
                if($ticket->num_ticket == $i) {
                    $ar[$i] = $ticket;
                } else {
                    $ar[$i] = [];
                }
            }
            $i++;
        } while($i <= $slots->max_tickets);

        return $ar;

And here is what I get:
{"2":[],"3":[],"4":[],"5":[],"6":{"id":3,"user_id":1,"slot_id":2,"num_ticket":6,"created_at":"2018-03-31 00:00:00","updated_at":"2018-03-31 00:00:00"},"7":[],"8":[],"9":[],"10":[]}

The loop works correctly only on 3 objects. There are three of them, in which num_ticket wounds are 2, 5 and 6. Why does it work only on 6. I tried to substitute 2 or 5 manually instead of $i, then it returns all 10 empty objects in the json response.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Shapoval, 2018-03-31
@sanek_os9

$tickets = Ticket::where('slot_id', $slot_id)->get();
        $ar = [];
        $slots = Slot::find($slot_id);

        $i = 2;
        do {
            foreach (json_decode($tickets) as $ticket) {
                if($ticket->num_ticket == $i) {
                    $ar[$i] = $ticket;
                }
            }
            $i++;
        } while($i <= $slots->max_tickets);

        return $ar;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question