简体   繁体   中英

Set array value in a for loop php

Apologies for the dumb question, I just can't seem to understand what's exactly going on. I have a JS function which I transformed into PHP and in the JS everything is working as desired. The problem with the PHP one is here I believe: I have last element of and array which I get by

$lastPeriod = end($periods);

while being in a for loop. Next I set the value of $lastPeriod['closeTime'] to equal a number. If I dd($lastPeriod) after changing it's value it is updated, however if I dd(); at the end it is not. Maybe there is a conflict with how I remove the next element so the end is not working correctly?

    for ( $i = 0; $i < sizeof($dailyHours); $i++ )
    {
        $periods = $dailyHours[$i]['periods'];

        for ($j = 0; $j < sizeof($periods); $j++)
        {
            $lastPeriod = end($periods);
                if ($lastPeriod['closeTime'] === '00:00'
                    && $dailyHours[$i + 1]['periods'][0]['openTime'] === '00:00'
                    && $dailyHours[$i + 1]['periods'][0]['closeTime'] !== '00:00')
                {
                    if (Carbon::parse($dailyHours[$i + 1]['periods'][0]['closeTime'])->isBefore(Carbon::createFromTimeString('11:59')))
                    {
                        $lastPeriod['closeTime'] = $dailyHours[$i + 1]['periods'][0]['closeTime'];
                        array_splice($dailyHours[$i + 1]['periods'], 0, 1);

                        if (sizeof($dailyHours[$i + 1]['periods']) < 1)
                        {
                            $dailyHours[$i + 1]['isOpen'] = 0;
                        }
                    }
                }
            }
        }
    }

The problem is that you are editing a copy of the array.

Let's look at this example:

<?php

$myPets = [
  [
    'animal' => 'cat',
    'name' => 'john'
  ], 
];

$pet = $myPets[0];
$pet['name'] = 'NewName';

var_dump($myPets);

When I run this program the name of my pet should be 'NewName' right?

array(1) {
  [0]=>
    array(2) {
      ["animal"]=>
        string(3) "cat"
      ["name"]=>
        string(4) "john"
    }
}

Well, as you can see the name hasn't changed. This is because when we do $pet = $myPets[0] PHP will make a copy of the $myPets[0] array.

To fix this you can take the reference of that array by doing: $pet = &$myPets[0] .

There are a few issues in the code:

In a loop you have this code:

$lastPeriod = end($periods);

Then later on you have:

$lastPeriod['closeTime'] = $dailyHours[$i + 1]['periods'][0]['closeTime'];

This should result in a warning

Warning: Cannot use a scalar value as an array in....

The issue that $lastPeriod = end($periods); gives you the value of the last element in the array. So if you have this array:

$dailyHours[0]['periods'][] = 23;
$dailyHours[0]['periods'][] = 12;
$dailyHours[0]['periods'][] = 5;
$dailyHours[0]['periods'][] = 8; //Last elements value in item 0

$dailyHours[1]['periods'][] = 23;
$dailyHours[1]['periods'][] = 11;
$dailyHours[1]['periods'][] = 3; //Last elements value in item 1

$dailyHours[2]['periods'][] = 5;
$dailyHours[2]['periods'][] = 12; //Last elements value in item 2

Therefore

$lastPeriod = end($periods);

would return the values 8,3 and 12.

A simplified version of your code with two loops. The outer loop ($i) and the inner loop ($j)

for ( $i = 0; $i < sizeof($dailyHours); $i++ ) {
    $periods = $dailyHours[$i]['periods']; 

    for ($j = 0; $j < sizeof($periods); $j++) {
        $lastPeriod = end($periods); //would give 8,8,8, 3,3,3 and 12,12,12

        //This would basically mean that an associative array with key closeTime
        //with the value of 8,3 or 12 => is the same as the value of $dailyHours[$i + 
        //1]['periods'][0]['closeTime'];
        //This is not a thing PHP can handle and therefore you should reviece
        //a warning "Cannot use a scalar value as an array..."
        //(You simply cannot mix numbers and associative arrays in that manner)
        $lastPeriod['closeTime'] = $dailyHours[$i + 1]['periods'][0]['closeTime'];
    }

}

Another issue is that you're trying to set a value each iteration with the same key and therefore nothing happens:

for ( $i = 0; $i < sizeof($dailyHours); $i++ ) {
    $periods = $dailyHours[$i]['periods'];

    for ($j = 0; $j < sizeof($periods); $j++) {
        $lastPeriod['closeTime'] = rand();        
        echo '<pre>';
        echo $lastPeriod['closeTime'];
        echo '</pre>';
    }

}

A possible output of the loops above code could be:

1393399136
1902598834
1291208498
654759779
493592124
1469938839
929450793
325654698
291088712

$lastPeriod['closeTime'] would be 291088712 which is the last set value above (last iteration) but the previous values set are not stored anywhere.

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