对于对象来说,“data[] = $var”等价于什么?
我正在循环执行 mysql 查询并将值存储到一个对象中。我想在将数据存储到对象时像数组一样自动迭代该对象。
这就是我正在做的:
$i = 0;
foreach( $query->result() as $row )
{
$data->$i = $row;
$i++;
}
我想模仿下面的代码,但是对于一个对象,消除上面代码中对 $i
的需要:
foreach( $query->result() as $row )
$data[] = $row;
什么相当于 $ data[] = $row
在 foreach 或 while 循环中存储变量时迭代对象?
注意:很明显,我不应该以这种方式使用对象。您能否详细说明一下为什么会出现这种情况?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
没有这样的东西,因为对象不是这样工作的。此外,如果您想以线性方式存储内容,那么您无论如何都不应该以这种方式使用对象。
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.
如果你想创建一个对象,你可以使用 foreach() 进行迭代,它必须实现迭代器接口,参见。 http://php.net/iterator
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 !