This may be a basic question but I am struggling with a way to count values without doing multiple foreach
loops. I have this array of objects (partial list included):
array(51) {
[0]=>
object(stdClass)#971 (4) {
["hole"]=>
string(1) "2"
["club"]=>
string(1) "6"
["shot_type"]=>
string(1) "6"
["shot_loc"]=>
string(1) "6"
}
[1]=>
object(stdClass)#970 (4) {
["hole"]=>
string(1) "2"
["club"]=>
string(2) "16"
["shot_type"]=>
string(1) "8"
["shot_loc"]=>
string(1) "1"
}
[2]=>
object(stdClass)#969 (4) {
["hole"]=>
string(1) "2"
["club"]=>
string(2) "19"
["shot_type"]=>
string(1) "3"
["shot_loc"]=>
string(1) "2"
}
[3]=>
object(stdClass)#968 (4) {
["hole"]=>
string(1) "1"
["club"]=>
string(1) "1"
["shot_type"]=>
string(1) "6"
["shot_loc"]=>
string(1) "6"
}
[4]=>
object(stdClass)#967 (4) {
["hole"]=>
string(1) "1"
["club"]=>
string(2) "15"
["shot_type"]=>
string(1) "5"
["shot_loc"]=>
string(1) "3"
}
The number of objects in the list vary but each object will have the key=>values
as shown. What I would like to return is an array with count of each of the values of "hole". Something like this:
`array(18) {
[1]=> 4
[2]=> 5
[3]=> 6`
and so on where the key is each of the values of "hole" and the new array value is the count.
I have attempted forms of count
, count(get_object_vars($))
, and others but all examples I find are counting the objects. Thanks in advance.
Your question is a bit confusing, but this should do the trick for you:
$holes = [];
foreach ($array as $object) {
if (isset($object->hole)) {
$hole = $object->hole;
if (!isset($holes[$hole])) {
$holes[$hole] = 0;
}
$holes[$hole]++;
}
}
I tested it using this:
$object1 = (object)['hole'=>'2'];
$object2 = (object)['hole'=>'3'];
$object3 = (object)['hole'=>'1'];
$object4 = (object)['hole'=>'3'];
$array = [$object1,$object2,$object3,$object4];
$holes = [];
foreach ($array as $object) {
if (isset($object->hole)) {
$hole = $object->hole;
if (!isset($holes[$hole])) {
$holes[$hole] = 0;
}
$holes[$hole]++;
}
}
echo "<pre>";
print_r($holes);
Prints
Array
(
[2] => 1
[3] => 2
[1] => 1
)
It sounds like you want an array of 18 (?) elements returned with the count of number of occurences of each hole.
$new_array = array_reduce($your_array, function ($carry, $item) {
if (property_exists($item, "hole") && array_key_exists($item->hole - 1, $carry)) {
$carry[$item->hole - 1]++;
}
return $carry;
}, array(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0));