简体   繁体   English

多维数组总和列

[英]Multidimensional Array Sum Column

I have a multidimensional array with a race type column and a boats column (which has the total number of boats for each race type). 我有一个带有比赛类型列和列的多维数组(该列包含每种比赛类型的船总数)。 This is how I am getting the array values: 这就是我获取数组值的方式:

$boats = $wpdb->get_results("
        select rt.race_type
              ,sum(tr.boat_count) boats
          from registrations tr
         group by rt.race_type;
");

The array works perfectly fine. 数组工作得很好。 But now I am trying to get the total number of boats for all race types (without using a loop). 但是现在我正在尝试获取所有种族类型的船只总数(不使用循环)。 After some research, I have tried the code below, but it doesn't seem to be working: 经过研究,我尝试了下面的代码,但似乎无法正常工作:

$totalboats = array_sum(array_column($boats,'boats'));

When I run the following command: 当我运行以下命令时:

echo $totalboats;

The result of that is 0, which is clearly wrong. 其结果为0,这显然是错误的。

Any ideas? 有任何想法吗? I am running PHP 5.6.29. 我正在运行PHP 5.6.29。

================== EDIT 01 ================== ==================编辑01 ===================

As requested, here is the var_dump of $boats : 根据要求,这是$ boatsvar_dump

array(2) {
    [0]=>
        object(stdClass)#672 (2) {
            ["race_type"]=> string(12) "Elite 8-Hour"
            ["boats"]=> string(1) "2"
        }
    [1]=>
        object(stdClass)#673 (2) {
            ["race_type"]=> string(12) "Sport 4-Hour"
            ["boats"]=> string(1) "2"
        }
}

The problem is that your $boats sub-elements are objects and not arrays. 问题是您的$boats子元素是对象而不是数组。 array_column doesn't work with objects in PHP5 (it does in PHP7, though). array_column不适用于PHP5中的对象(尽管在PHP7中适用)。

You could use a workaround using array_map , as shown in this answer to a previous question : 您可以使用array_map解决方法,如上一个问题的答案所示:

$totalboats = array_sum(
    array_column(
        array_map(
            function($o){
                return (array)$o;
            },
            $boats),
       'boats')
    );
echo $totalboats; // echoes "4"

If your variable is array and not object you can use this 如果变量是数组而不是对象,则可以使用此变量

$array = [
  0 => [
     'race_type' => 'Elite 8-Hour',
     'boats' => '2',
    ],
  1 => [
     'race_type' => 'Sport 4-Hour',
     'boats' => '2',
    ]
];



$toSum = array_sum(array_column($array, 'boats'));

echo "<pre>";print_r($toSum);die;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM