Foreach array on array php

I'm trying to foreach my arrays but not working

this is my Controller

    $start    = (new DateTime("2016-11-01"))->modify('first day of this month');
    $end      = (new DateTime("2017-02-01"))->modify('first day of next month');
    $interval = DateInterval::createFromDateString('1 month');
    $period   = new DatePeriod($start, $interval, $end);
    $result = array();

    foreach ($period as $dt) {
        $data_month = array(
            'month' => $dt->format("n"),
            'year'  => $dt->format("Y")
        );
        array_push($result, $data_month);
    }

and this is my blade

@foreach($result as $row => $innerArray)
   @foreach($innerArray as $innerRow => $value)
   <td>{{$value->month}}</td>
   <td>{{$value->year}</td>
   @endforeach
@endforeach

result:

Trying to get property of non-object

but if I try like this just only first value on the array ('month') are looping

@foreach($result as $row => $innerArray)
   @foreach($innerArray as $innerRow => $value)
   <td>{{$value}}</td>
   @endforeach
@endforeach

result:

looping month only

Upvotes: 2

Views: 85

Answers (3)

Jigar Prajapati
Jigar Prajapati

Reputation: 112

Controller Logic

    $start    = (new DateTime("2016-11-01"))->modify('first day of this month');
    $end      = (new DateTime("2017-02-01"))->modify('first day of next month');
    $interval = DateInterval::createFromDateString('1 month');
    $period   = new DatePeriod($start, $interval, $end);
    $result = array();

    foreach ($period as $dt) {
        $result[] = array(
            'month' => $dt->format("n"),
            'year'  => $dt->format("Y")
        );
    }

Blade file

@foreach($result as $row => $data) 
    <td>{{$data['month']}}</td>
    <td>{{$data['year']}}</td>
@endforeach

Upvotes: 1

Rp9
Rp9

Reputation: 1963

try this

@foreach($result as $result1)
  {{ $result1['month'] }}
@endforeach

Upvotes: 0

Lawrence Cherone
Lawrence Cherone

Reputation: 46602

Try this:

@foreach($result as $value)
   <td>{{ $value['month'] }}</td>
   <td>{{ $value['year'] }</td>
@endforeach

Because the array is structured like:

Array
(
    [0] => Array
        (
            [month] => 11
            [year] => 2016
        )

    [1] => Array
        (
            [month] => 12
            [year] => 2016
        )

    [2] => Array
        (
            [month] => 1
            [year] => 2017
        )

    [3] => Array
        (
            [month] => 2
            [year] => 2017
        )

)

Upvotes: 2

Related Questions