php 致命错误:不能使用 stdClass 类型的对象作为数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5412924/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Fatal error: Cannot use object of type stdClass as array in
提问by kyle
I'm getting the error:
我收到错误:
"Fatal error: Cannot use object of type stdClass as array in" on line 183
第 183 行的“致命错误:无法使用 stdClass 类型的对象作为数组”
From this code:
从这个代码:
$getvidids = $ci->db->query(
"SELECT * FROM videogroupids " .
"WHERE videogroupid='$videogroup' AND used='0' LIMIT 10");
foreach ($getvidids->result() as $row){
$vidid = $row['videoid']; //This is line 183
}
Anyone know what's wrong with the above code? Or what this error means?
有人知道上面的代码有什么问题吗?或者这个错误是什么意思?
回答by BoltClock
CodeIgniter returns result rows as objects, not arrays. From the user guide:
CodeIgniter 将结果行作为对象而不是数组返回。从用户指南:
result()
This function returns the query result as an array of objects, or an empty arrayon failure.
结果()
此函数以对象数组或失败时的空数组形式返回查询结果。
You'll have to access the fields using the following notation:
您必须使用以下表示法访问字段:
foreach ($getvidids->result() as $row) {
$vidid = $row->videoid;
}
回答by icchanobot
if you really want an array instead you can use:
如果你真的想要一个数组,你可以使用:
$getvidids->result_array()
which would return the same information as an associative array.
这将返回与关联数组相同的信息。
回答by WalterV
Controller(Example: User.php)
控制器(例如:User.php)
<?php
defined('BASEPATH') or exit('No direct script access allowed');
class Users extends CI_controller
{
// Table
protected $table = 'users';
function index()
{
$data['users'] = $this->model->ra_object($this->table);
$this->load->view('users_list', $data);
}
}
View(Example: users_list.php)
查看(例如:users_list.php)
<table>
<thead>
<tr>
<th>Name</th>
<th>Surname</th>
</tr>
</thead>
<tbody>
<?php foreach($users as $user) : ?>
<tr>
<td><?php echo $user->name; ?></td>
<td><?php echo $user->surname; ?></th>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<!-- // User table -->
回答by Bilal Khalid
Sorry.Though it is a bit late but hope it would help others as well . Always use the stdClass object.e.g
对不起。虽然有点晚了,但希望它也能帮助其他人。始终使用 stdClass object.eg
$getvidids = $ci->db->query("SELECT * FROM videogroupids WHERE videogroupid='$videogroup' AND used='0' LIMIT 10");
foreach($getvidids->result() as $key=>$myids)
{
$vidid[$key] = $myids->videoid; // better methodology to retrieve and store multiple records in arrays in loop
}