dongtigai3875
dongtigai3875
2016-07-23 15:03

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

  • laravel
  • database
  • php
  • arrays
  • hashmap

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条回答