简体   繁体   中英

Laravel php foreach Loop get value by key

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM