开发者

How to iterate over an array of objects without foreach and ArrayAccess

开发者 https://www.devze.com 2023-01-01 18:17 出处:网络
I\'m having to dev开发者_运维知识库elop a site on PHP 5.1.6 and I\'ve just come across a bug in my site which isn\'t happening on 5.2+. When using foreach() to iterate over an object, I get the follow

I'm having to dev开发者_运维知识库elop a site on PHP 5.1.6 and I've just come across a bug in my site which isn't happening on 5.2+. When using foreach() to iterate over an object, I get the following error: "Fatal error: Objects used as arrays in post/pre increment/decrement must return values by reference..."

Does anyone know how to convert the following foreach loop to a construct which will work with 5.1.6? Thanks in advance!

foreach ($post['commercial_brands'] as $brand)
                    {
                        $comm_food = new Commercial_food_Model;
                        $comm_food->brand = $brand;
                        $comm_food->feeding_type_id = $f_type->id;
                        $comm_food->save();
                    }


Improving upon Coronatus's answer:

$max = count($post['commercial_brands']);
for ($i = 0; $i < $max; $i++)
{
    $comm_food = new Commercial_food_Model;
    $comm_food->brand = $post['commercial_brands'][$i];
    $comm_food->feeding_type_id = $f_type->id;
    $comm_food->save();
}

You should never have a function in the condition of a loop, because each time the loop goes around it will run the function.


$x = 0;
$length = count($post['commercial_brands']);
while($x < $length){
     $comm_food = new Commercial_food_Model;
     $comm_food->brand = $post['commercial_brands'][$x];
     $comm_food->feeding_type_id = $f_type->id;
     $comm_food->save();
     $x++;
}

//while 4 eva


for ($i = 0; $i < count($post['commercial_brands']); $i++)
{
    $comm_food = new Commercial_food_Model;
    $comm_food->brand = $post['commercial_brands'][$i];
    $comm_food->feeding_type_id = $f_type->id;
    $comm_food->save();
}
0

精彩评论

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