错误“无法将stdClass类型的对象用作数组".从Laravel数据库查询结果访问明显存在的整数类型数据时

错误“无法将stdClass类型的对象用作数组

问题描述:

我从Laravel数据库查询命令中获取了数据:

I got my data from Laravel database query command:

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

当我var转储数据时,我得到:

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
}

我要访问max_question_display.但是当我这样做时:

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

var_dump($group["max_question_display"]);

PHP返回错误Cannot use object of type stdClass as array.

当我这样做时:

var_dump($group->max_question_display);

我得到:

int(5)

但是我不想要int.我只想要5.以整数形式.

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

如果我foreach循环$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.

我还尝试获取array的第一个元素,以为这可能是一个包含1个元素的数组,但是也会引发相同的错误.

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.

我得到的关于此错误的一般答案是"stdClass不是数组".我已经浏览了几个与我的标题相似的问题,但是没有一个来自Laravel DB的地址对象.当我阅读Laravel DB上的手册时,可以放心的是,我可以像简单的字典/哈希图一样访问返回的数据.

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.

对不起,我了解我非常非常的新手错误.无需回答.谢谢.

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

注意第一个var_dump的第一行:

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);

在输出中看到(int)的原因是var_dump函数在值旁边显示值类型.要访问该值,请执行

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;

如果您想在屏幕上看到没有类型的文字,请使用echo

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

echo $group->max_question_display; // 5