如何统计stdClass Object中嵌套数组[tickets]的元素数量?
Correct Way to Count Entries in the
tickets Array from a stdClass Object Hey there! Let's fix this ticket count issue once and for all. The core problem here is that you're targeting the wrong part of your object—you need to access the tickets array directly, not the parent object itself.
The Correct Solution
Since $result is a stdClass object with a tickets property that holds your array, you can simply access that property and use count() on it:
// Directly count the entries in the tickets array $totalTickets = count($result->tickets); echo $totalTickets;
This will give you the exact number of entries inside the tickets array, whether it's 100+ or any other number.
Why Your Previous Methods Failed
Let's break down what went wrong with each approach:
array_count_values()error: You passed the entire$resultobject to this function, but it requires an array as input. Even if you had passed$result->tickets, this function counts value frequencies—not total entries—socount()is still the right tool for your goal.- Loop counting: Your loop iterated over the parent
$resultobject, not theticketsarray. This means you were counting the number of properties in the$resultobject (which is why you got a tiny number instead of the 100+ entries you expected). count((array)$result): Converting the entire$resultobject to an array counts the number of properties in the object, not the elements inside theticketsarray. The result of 4 means your$resultobject has 4 properties total, withticketsbeing just one of them.
Optional: Add Safety Checks
To handle cases where tickets might not exist or isn't an array, you can add some guard clauses:
if (isset($result->tickets) && is_array($result->tickets)) { $totalTickets = count($result->tickets); echo $totalTickets; } else { echo "No tickets found, or the tickets property is not an array."; }
内容的提问来源于stack exchange,提问作者pcgben
相关产品推荐
相关产品推荐

