开发者

What is the equivalent of `data[] = $var` for an object?

开发者 https://www.devze.com 2023-03-28 21:06 出处:网络
I\'m looping through a mysql query and storing the values to an object.I want to automatically iterate the object like one would an array as I store the data to it.

I'm looping through a mysql query and storing the values to an object. I want to automatically iterate the object like one would an array as I store the data to it.

Here is what I'm doing:

$i = 0;
foreach( $query->result() as $row )
{
    $data->$i = $row;
    $开发者_运维知识库i++;
}

I'd like to mimic the code below, but for an object, removing the need for $i in the above code:

foreach( $query->result() as $row )
    $data[] = $row;

What is the equivalent to $data[] = $row to iterate an object as you store variables to it in a foreach or while loop?

NOTE: It's clear that I shouldn't be using objects in this manner. Could you please elaborate on why this is the case?


There isn't one, because objects don't work that way. Besides, if you want to store things in a linear fashion then you shouldn't be using an object in that manner regardless.


If you want to create an object you can iterate using foreach() it has to implement the iterator-interface, cf. http://php.net/iterator


you can use an array for storing data, then convert it to an object afterwards !

0

精彩评论

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