mannyotr
mannyotr

Reputation: 83

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.

Any ideas? I am running PHP 5.6.29.

================== EDIT 01 ==================

As requested, here is the var_dump of $boats:

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

Upvotes: -1

Views: 1127

Answers (2)

Priyank
Priyank

Reputation: 1328

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;

Upvotes: 0

roberto06
roberto06

Reputation: 3864

The problem is that your $boats sub-elements are objects and not arrays. array_column doesn't work with objects in PHP5 (it does in PHP7, though).

You could use a workaround using array_map, as shown in this answer to a previous question :

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

Upvotes: 2

Related Questions