Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 197
  • Last Modified:

PHP Get Column Totals for data in a Two Dimensional Array

I'm trying to total the columns in a two-dimensional array without much success.

Array look like:

object(stdClass)[685]
      public 'fusWeek' => string '45' (length=2)
      public 'Avg2012' => string '7.71' (length=4)
      public 'Avg2013' => string '7.84' (length=4)
      public 'Avg2014' => null
      public 'Avg2015' => null

I'm using the following code to do the calculation but just keep getting zero as the total

  $column = array_column($ary_table_data, 'Avg2012');
  $totals = array_sum($column);

Open in new window


I know that the data in each column is a number but is held as a string, but was hoping PHP was clever enough to translate this.

Any other ideas or thoughts on how I can get this total to work out correctly.
0
Sean Clarke
Asked:
Sean Clarke
  • 2
1 Solution
 
COBOLdinosaurCommented:
I think you will need to convert the stings to float usinf floatval()

See http://php.net/manual/en/function.floatval.php

once you have the data converted, array_sum() should work

Cd&
0
 
Ray PaseurCommented:
PHP can be helpful here if you "ask nicely" :-)

<?php // demo/temp_sean_clarke.php
error_reporting(E_ALL);

/** 
 * SEE: http://www.experts-exchange.com/Programming/Languages/Scripting/PHP/Q_28597329.html
 *
 * object(stdClass)[685]
 *      public 'fusWeek' => string '45' (length=2)
 *      public 'Avg2012' => string '7.71' (length=4)
 *      public 'Avg2013' => string '7.84' (length=4)
 *      public 'Avg2014' => null
 *      public 'Avg2015' => null
 */

// TEST DATA FROM THE POST AT E-E 
$obj = new StdClass;
$obj->fusWeek ='45';
$obj->Avg2012 ='7.71';
$obj->Avg2013 ='7.84';
$obj->Avg2014 = null;
$obj->Avg2015 = null;

// DOES THIS TEST DATA LOOK LIKE THE EXAMPLE?  YES.
var_dump($obj);

// MAKE IT INTO AN ARRAY SO WE CAN USE ARRAY_SUM()
$arr = (array)$obj;
$sum = array_sum($arr);
var_dump($sum);

Open in new window

0
 
Sean ClarkeAuthor Commented:
Perfect thanks.
It was casting the stdClass to an array that sorted it out
0
 
Ray PaseurCommented:
Thanks for the points.  PHP has some object iterators that can help, too.  But the shortest path is just recasting the data type.
0

Featured Post

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now