Thomas Charlesworth
Thomas Charlesworth

Reputation: 1839

Laravel foreach with chance that index is different

I have a loop where there are objects that the index changes. As you can see in our first object we have tv and the second has gv. The problem is, I want to loop over all the objects with the blade foreach loop that laravel provides. (This data is sent as an array, I just put it as JSON for reading)

[
 {
  "items" : {
    "pv" : "0",
    "tv" : "0",
    "ov" : "0"
  }
},
{
  "items" : {
    "pv" : "0",
    "gv" : "0",
    "ov" : "0"
   }
 }
]

This is what I could come up in terms of logic but I still get returned with Undefined index: tv

@foreach($products as $product)
<tr>
    <td>{{$product['items']['pv']}}</td>
    <td>
         @if( empty($product['items']['tv']) ) 
             {{$product['items']['gv']}}
         @else
             {{$product['items']['tv']}}
         @endif
    </td>
    <td>{{$product['items']['ov']}}</td>
</tr>
@endforeach

Upvotes: 0

Views: 252

Answers (1)

Thomas Charlesworth
Thomas Charlesworth

Reputation: 1839

     @if( array_key_exists('tv',$product['value']) ) 
        {{$product['value']['tv']}}
     @else
        {{$product['value']['gv']}}
     @endif

Upvotes: 0

Related Questions