Ad

Laravel Php Foreach Loop Get Value By Key

- 1 answer

I think im getting this simple thing confused. I just want to get the value of my key 'weeks' and 'days'. I have tried the following:

@foreach($years as $key3 => $year)
                <h1>{{$key3}}</h1>
                @foreach($year as $key2 => $months)
                    <p>{{$key2}}</p>
                    @foreach($months as $key1 => $days)
                        <p>{{$days['weeks']}}</p>
                        <p>{{$days->weeks}}</p> //try two//
                    @endforeach
                @endforeach
            @endforeach

which responds with this error:

Illegal string offset 'weeks'

this is an example of the array im trying to loop:

    array:4 [▼
  2016 => array:12 [▼
    "01" => array:2 [▼
      "weeks" => 5
      "days" => "31"
    ]

can someone help me understand what I am doing wrong?

Ad

Answer

You don't need the last foreach,

@foreach($years as $key => $year)
   <h1>{{$key}}</h1>
   @foreach($year as $key => $months)
        <p>{{$key}}</p>
        {{ $months['weeks'] }}
        {{ $months['days'] }}
   @endforeach
 @endforeach

Days isn't an array. But month is containing the keys: weeks and days. If you want object notation (->) just cast it to an object by typing (object) before the array.

Ad
source: stackoverflow.com
Ad