How to count objects in an array that have a certain value (PHP)
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') {
$in开发者_JAVA技巧complete[] = $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.
$complete = array_filter($timeslotlist, function($slot) {
return $slot->status == 'complete';
});
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:
function timeslot_filer($list, $status)
{
$result = array();
foreach($list as $slot)
if($slot->status == $status)
$result[] = $slot;
return $result;
}
You can then grab all slots with a certain status by just doing
$complete = timeslot_filter($timeslotlist, 'complete');
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.
There is no dedicated function in PHPs core to do something like this. However, you could possibly do some magic with array_walk()
, array_reduce()
or array_filter()
. However, I doubt this will gain you anything, neither nicer code nor speed improvement. I'd rather encapsulate the code you showed into a nice small object and just count instead of creating the status arrays.
Is this more complicated than I think it is? This seems like it should be very simple to do with just a regular array:
$statuses = array();
foreach ($timeslotlist->timeslot as $timeslot) {
$status = $timeslot->status;
//This block is just to avoid a notice; not mandatory.
if (!isset($statuses[$status])) {
$statuses[$status] = 0;
}
$statuses[$status]++;
}
print_r($statuses);
精彩评论