Home > Blockchain >  How can i have nested loop for two different arrays in laravel
How can i have nested loop for two different arrays in laravel

Time:10-11

I am trying to display the distance for each of my drivers on my database in my view.

When I do die or dump for $pickupDistanceAndTime2 it returns the arrays below, so I need each of the drivers to have its own distance.

0 => array:2 [▶]
1 => array:2 [▶]
2 => array:2 [▶]
return view('driverspane', [
    'drivers' => $driver,
    'rideDistancenTime' => $pickupDistanceAndTime2,
]);

In my view I am looping but not getting the way I want it to appear.

@foreach ($drivers as $item)
    @foreach ($rideDistancenTime as $data)
        {{ $data[0] }}
    @endforeach
@endforeach

But the above code keeps repeating distance and time for each of the driver but I want each of the driver to have its own distance and time only, please see the result I am getting below attached. enter image description here

The array for $driver returns

#items: array:3 [▼
    0 => App\Driver {#317 ▶}
    1 => App\Driver {#300 ▶}
    2 => App\Driver {#281 ▶}
  ]

CodePudding user response:

From what you did above, you are just repeating the same values for the first index of the array. You should not do a nested foreach statement.

Rather you could do it this way(using a for statement, provided that the arrays all have same number of keys:

 @for ($i=0; $i<count($drivers); $i  )
      
      {{$rideDistancenTime[$i][1]}}
      
@endfor

Now it should loop properly.

CodePudding user response:

You can use below code to achieve your goal:

$rideDistancenTime;

@foreach ($drivers as $key => $item)
    
      {{ $rideDistancenTime[$key] }}

@endforeach```
  • Related