如何访问计数的数组值

时间:2019-02-08 10:43:22

标签: laravel eloquent

如何访问COUNT(*)数组的值?我尝试使用$availableRooms[3]['COUNT(*)']

时收到错误消息“无法将stdClass类型的对象用作数组”
Array
(
    [0] => stdClass Object
        (
            [category] => king
            [COUNT(*)] => 3
        )

    [1] => stdClass Object
        (
            [category] => family
            [COUNT(*)] => 7
        )

    [2] => stdClass Object
        (
            [category] => quad
            [COUNT(*)] => 8
        )

    [3] => stdClass Object
        (
            [category] => standard
            [COUNT(*)] => 7
        )

)

我需要获取count的值。在这种情况下,当我使用$availableRooms[3]['COUNT(*)']时,它应该输出7

**EDIT**

查询

$availableRooms = DB::select("SELECT
      category, COUNT(*)
      FROM available_rooms
      WHERE NOT EXISTS (
          -- room is booked on the requested dates (...not)
          SELECT 1
          FROM room_reserveds
          JOIN bookings ON room_reserveds.bookingID = bookings.bookingID
          WHERE room_reserveds.roomID = available_rooms.roomID
          AND $checkOutDate > checkIndate
          AND $checkInDate < checkOutDate
      )
      GROUP BY category");

1 个答案:

答案 0 :(得分:1)

数组包含对象,因此您不能使用数组符号来获取这些属性。并且由于它是一个特殊键,因此您可以通过将名称放在{}之间作为字符串来获取属性。

$availableRooms[3]->{'COUNT(*)'};

我想这个结果来自数据库查询。更好的解决方案是为该结果提供一个可以直接引用的别名。

// SQL: 
SELECT COUNT(*) AS count FROM ...

// PHP:
$availableRooms[3]->count;