4

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?

4
  • Code smell: You probably should use different names for different keys of different arrays. Commented Jan 22, 2016 at 22:41
  • can you explain what you mean? Commented Jan 22, 2016 at 22:43
  • See L1, L3 and L5? They all share the same variable name $key as the key to your nested foreach loops. You should rename them to different names so you don't mix them up. (Normally the inner $key will overwrite the outer $key, but this is good practice) Commented Jan 22, 2016 at 22:47
  • okay, good to know. I thought $key was just the name of the positon. Commented Jan 22, 2016 at 22:49

1 Answer 1

7

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Why didn't I need the last foreach?
@RickiMoore because as your array example shows "01" is a month containing an array. That array contains only 2 keys with a value and not another array. So looping through month will only return the values.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.