Rei
Rei

Reputation: 323

How to access array value of count

How do I access the value of the array of COUNT(*)? I get the error Cannot use object of type stdClass as array when i tried to use $availableRooms[3]['COUNT(*)']

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
        )

)

I need to get the value of count. In this case when i use $availableRooms[3]['COUNT(*)'] it should output 7

**EDIT**

Query

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

Upvotes: 0

Views: 191

Answers (1)

Jerodev
Jerodev

Reputation: 33186

The array contains objects, so you can't use the array notation to get these properties. And because it's a special key, you can get the property by placing the name between {} as a string.

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

I suppose this results comes from a database query. A better solution would be to give this result an alias that can be referenced directly.

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

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

Upvotes: 1

Related Questions