vincent villafuerte
vincent villafuerte

Reputation: 13

How to make an array from foreach?

How to make this array from foreach in my code?

Below is my code

Array
(
    [0] => Array
        (
            [day] => 2016-11-21
        )

    [1] => Array
        (
            [day] => 2016-11-22
        )

    [2] => Array
        (
            [day] => 2016-11-23
        )

    [3] => Array
        (
            [day] => 2016-11-24
        )

    [4] => Array
        (
            [day] => 2016-11-25
        )
)

Below is my code but the result is different.

The result is from foreach and I want it to be an array, just like the array above.

    foreach ($data['my_undertime'] as $undertime_row) {

        $datetimein = new DateTime($undertime_row->timein);
        $datetimein->format('h:m:s');

        $datetimeout = new DateTime($undertime_row->timeout);
        $datetimeout->format('h:m:s');

        $items = array();

        if ($datetimein->format('h:m:s') > $undertime_row->beg_time && $datetimeout->format('h:m:s') < $undertime_row->end_time) {
            // echo $undertime_row->day;

            $items[]['day'] = $undertime_row->day;
        }

        echo "<pre>";
        print_r($items);


    }

Please help.

Thanks.

Upvotes: 0

Views: 120

Answers (2)

Exprator
Exprator

Reputation: 27513

$items = array();
$i = 0;
foreach ($data['my_undertime'] as $undertime_row) {

        $datetimein = new DateTime($undertime_row->timein);
        $datetimein->format('h:m:s');

        $datetimeout = new DateTime($undertime_row->timeout);
        $datetimeout->format('h:m:s');



        if ($datetimein->format('h:m:s') > $undertime_row->beg_time && $datetimeout->format('h:m:s') < $undertime_row->end_time) {
            // echo $undertime_row->day;

            $items[$i]['day'] = $undertime_row->day;
        }
 $i++;



    }
       echo "<pre>";
        print_r($items);

try this

Upvotes: 0

axiac
axiac

Reputation: 72226

The problem is in the line $items = array();.

As it is now, $item is recreated on each loop. After the foreach it ends up remembering only the last iteration of the loop.

If you want to keep all the data in $item then move this line of code before the foreach loop.

Upvotes: 1

Related Questions