从STDClass获得价值 [英] Get value from STDClass

查看:88
本文介绍了从STDClass获得价值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用PHP和CodeIgniter.我使用以下脚本运行查询:

I'm using PHP and CodeIgniter. I ran a query using the following script:

$query = $this->db->query('select login_id, date_created from prjsite_login');
$row = $query->result();
print_r($row);

print_r的结果是:

The result of the print_r is:

Array([0] => stdClass对象([login_id] => admin [创建日期] =>2018-04-04 13:18:42))

Array ( [0] => stdClass Object ( [login_id] => admin [date_created] => 2018-04-04 13:18:42 ) )

这是正确的.当您尝试使用以下脚本从stdClass提取1个对象或值时:

Which is correct. Thou when I tried to fetch 1 object or value from stdClass using the following script:

echo $query->login_id;

我收到以下错误:

遇到PHP错误

严重性:通知

消息:试图获取非对象的属性

Message: Trying to get property of non-object

文件名:pages/home.php

Filename: pages/home.php

行号:21

回溯:

文件:C:\ xampp \ htdocs \ BMI_PRJSITE \ application \ views \ pages \ home.php行:21函数:_error_handler

File: C:\xampp\htdocs\BMI_PRJSITE\application\views\pages\home.php Line: 21 Function: _error_handler

文件:C:\ xampp \ htdocs \ BMI_PRJSITE \ application \ controllers \ Pages.php行:11功能:查看

File: C:\xampp\htdocs\BMI_PRJSITE\application\controllers\Pages.php Line: 11 Function: view

文件:C:\ xampp \ htdocs \ BMI_PRJSITE \ index.php行:315功能:require_once

File: C:\xampp\htdocs\BMI_PRJSITE\index.php Line: 315 Function: require_once

我在做什么错了?

TIA

推荐答案

您不能直接从$ query获取值,因为这时您只是在生成查询,并且只有在执行后才能从$ query获取结果.您正在

You cannot directly get a value from $query because at this point you are just generating a query and you will get the result from $query only after executing it which you are doing at

$row=$query->result();

查看结果,您得到的结果是stdClass对象的数组,因此需要对对象进行json编码,然后将其解码回数组

Looking at your result you are getting a result as an array of a stdClass object so need to json-encode your object and then decode it back to an array

$array = json_decode(json_encode($row), True);

如果您确定只会得到一行,那么就不需要循环,您只需通过

If you are sure you will get only one row then no need for loop and you can simply do it by

echo $array[0]->login_id;

否则,您必须去循环

 foreach ($array as  $value) {
        echo $value->login_id;
    }

这篇关于从STDClass获得价值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆