dongtigai3875 2016-07-23 15:03
浏览 213
已采纳

从Laravel Database查询结果访问明确存在的整数类型数据时出错“无法使用stdClass类型的对象作为数组”

I got my data from Laravel database query command:

$group = DB::table('groups')->where("id", $group_id)->first();

When I var dump my data, I get:

object(stdClass)#200 (7) {
  ["id"]=>
  int(1)
  ["levels_id"]=>
  int(1)
  ["title"]=>
  string(8) "Novice 1"
  ["description"]=>
  string(11) "Lorem Ipsum"
  ["max_question_display"]=>
  int(5)
  ["created_at"]=>
  NULL
  ["updated_at"]=>
  NULL
}

I want to access the max_question_display. But when I do:

var_dump($group["max_question_display"]);

PHP returns error Cannot use object of type stdClass as array.

When I do:

var_dump($group->max_question_display);

I get:

int(5)

But I don't want the int. I only want the 5. In integer form.

If I foreach loop the $group:

foreach ($group as $t) {
    echo "<pre>";
    var_dump($t);
    echo "</pre>";
}

I get each of the data as a single data each loop.

int(1)
int(1)
string(8) "Novice 1"
string(11) "Lorem Ipsum"
int(5)
NULL
NULL

This is obviously also not the way the result accessed that I'm looking for.

I also tried to get the first element of array, thinking that this might be an array with 1 element, but that also raise the same error.

I get it that the general answer in this site about this error is that "stdClass is not array". I have browsed several question with similar title like mine, but nothing address object that came from Laravel DB. When I read the manual on Laravel DB, I was assured that I can access the data returned like a simple dictionary / hashmap.

EDIT: Sorry, I understand my very, very newbie mistakes. No need to answer this. Thanks.

  • 写回答

2条回答 默认 最新

  • dongliuxia9495 2016-07-23 15:09
    关注

    Notice the first line of your first var_dump:

    object(stdClass)#200
    

    Because you're dealing with an object, you access its properties with ->. When you do:

    var_dump($group->max_question_display);
    

    The reason you see (int) in the output is that the var_dump function shows the value type, next to the value. To access the value, do

    $group->max_question_display;
    

    If you want to see it on screen without the type, use echo

    echo $group->max_question_display; // 5
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题