0

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");
4
  • 1
    You can use alias on your query like COUNT(*) as count Commented Feb 8, 2019 at 10:44
  • Objects and array use different notation to access values: -> for objects [] for arrays Commented Feb 8, 2019 at 10:45
  • show your database query Commented Feb 8, 2019 at 10:45
  • @SaurabhMistry see eidit Commented Feb 8, 2019 at 10:47

1 Answer 1

1

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;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.