I’m using an array $timeslotlist that contains multiple “timeslot” objects. Each timeslot has multiple values, one of which is “status”. I’m having trouble figuring out how to count the number of timeslots with a certain status.
I’d like to do something similar to count_array_values($timeslotlist) and end with an array that has all the possible keys and the number of times they occur, but I’m running into problems because the array is filled with objects.
I’m left with creating new arrays for each value I’m looking for, and iterating through the array with timeslots and adding those with the value I’m looking for into the new array:
$complete = array();
$incomplete = array();
foreach ($timeslotlist->timeslot as $timeslot) {
if ($timeslot->status == 'complete') {
$complete[]=$timeslot;
}
elseif ($timeslot->status == 'incomplete') {
$incomplete[] = $timeslot;
}
}
$incomplete_count = count($incomplete);
$complete_count = count($complete);
Is there any quicker/simpler way to work with objects inside of an array?
Thanks for any help!
You could use array_filter and pass in a anonymous function to get only the values you want.
If you don’t want to use array_filter and do not want to add a new condition in your foreach for every status, just turn it into a function:
You can then grab all slots with a certain status by just doing
Then it’s just a matter of
count($complete)to get the count.Is this what you’re looking for? If not, please let me know.