开发者

the reset function and associative arrays in php?

开发者 https://www.devze.com 2023-02-21 15:26 出处:网络
I\'m trying to loop through an associative array with the help of the functions current(), next() and reset(). The first two functions work great for m开发者_Python百科e but when I want to loop throug

I'm trying to loop through an associative array with the help of the functions current(), next() and reset(). The first two functions work great for m开发者_Python百科e but when I want to loop through it again and use the reset() function it won't work.

Here's the code:

while ($availability_per_date = mysql_fetch_assoc($availability)) {

    //it won't go in to the loop below a second time
    while (current($room_types_available)) {

        $key= key($room_types_available);

        if ($availability_per_date["{$key}"] == 0) {                
            $room_types_available["{$key}"] = 0;
        }
        echo $key;

        next($room_types_available);
    }
    reset($room_types_available);
}


First off, try to use built-in functions that can easily work better with your code, here's an example:

while ($availability_per_date = mysql_fetch_assoc($availability)) {
    //it won't go in to the loop below a second time
    foreach($room_types_available as $key=>$value){
        if ($availability_per_date["{$key}"] == 0) {                
            $room_types_available["{$key}"] = 0;
        }
        echo $key;
    }
}

If it gives any bugs with your app, post it and we'll fix :)


Is it possible that the return of current($room_types_available) the second time through returns a value that casts to false?

Using the each() function is a good way to solve the problem, it avoids ambiguity on false.


Not to copy on someone else's answer, but preinheimer is correct.

In the first iteration of the loop, you are setting a number of values to false (the string of "0" is false in PHP). While is then detecting these in subsequent calls and then terminating prematurely (because current, in this case, is returning false). Your two options are using each (as suggested by preinheimer) or foreach instead of while (as suggested by Khez).

Personally, (as I stated in the comments above), I view foreach as far more intuitive and therefore better practice, but neither of the two are functionally incorrect.

0

精彩评论

暂无评论...
验证码 换一张
取 消