计算PHP对象数组

时间:2016-04-15 01:14:45

标签: php arrays object

这可能是一个基本问题,但我正在努力研究一种在不进行多个foreach循环的情况下计算值的方法。我有这个对象数组(包括部分列表):

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"
  }

列表中的对象数量各不相同,但每个对象都会显示key=>values。我想要返回的是一个数组,其中包含" hole"的每个值的计数。像这样:

`array(18) {
  [1]=> 4
  [2]=> 5
  [3]=> 6`

等等,其中键是" hole"的每个值。并且新的数组值是计数。

我尝试过countcount(get_object_vars($))等形式,但我找到的所有例子都在计算对象。提前谢谢。

2 个答案:

答案 0 :(得分:0)

听起来你想要一个由18个(?)元素组成的数组,并返回每个洞的出现次数。

$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));

答案 1 :(得分:0)

你的问题有点令人困惑,但这应该适合你:

$holes = [];
foreach ($array as $object) {
    if (isset($object->hole)) {
        $hole = $object->hole;
        if (!isset($holes[$hole])) {
            $holes[$hole] = 0;
        }
        $holes[$hole]++;
    }
}

我用它测试了它:

$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);

打印

Array
(
    [2] => 1
    [3] => 2
    [1] => 1
)