impaler_78
impaler_78

Reputation: 19

failed to get values from arrays

good day gurus! got some problems to get the sum, max, min values in arrays

my script goes like this;

$result = mysql_query("SELECT date, reading FROM table "); 

$firstReading = 30089;

while($row = mysql_fetch_array($result)){
    $presentRow = $row['reading'];

    $consumption = (($presentRow - $firstReading));
    $firstReading = $presentRow; //back to presentRow
    echo "['".$row['date']."', ".$row['reading'].", ".$consumption."],";

it yields something like this;

['2016-10-01', 30153, 64],    
['2016-10-02', 30209, 56],    
['2016-10-03', 30253, 44],    
['2016-10-04', 30315, 62],    
['2016-10-05', 30373, 58],

echo array_sum(array_column($consumption, [2])); //to sum up all the value in third column

but when i called to sum up /max/min values of the (consumption) it echoes nothing. is there anything missing? need some help here. i want to get sum, max , min values of consumption.

i tried user def var in mysql set statement and it works however thers an error when i run it with php. here is my query (SET @firstreading:=30089; SELECT (reading-@firstreading) AS consumption, @firstreading:=reading FROM table) . it succeed in mysql but i have an error in the browser in running with php. error myqsl line 1 blah blah blah.... (the user define var itself)

Upvotes: 2

Views: 72

Answers (1)

jitendrapurohit
jitendrapurohit

Reputation: 9675

I think you need to re-write this and do it something like -

while($row = mysql_fetch_array($result)){
  $presentRow = $row['reading'];

  $consumption = (($presentRow - $firstReading));
  $firstReading = $presentRow; //back to presentRow

  //put every thing in array instead of a string.
  $data[] = array(
    'date' => $row['date'],
    'reading' => $row['reading'],
    'consumption' => $consumption,
  );
} //close the while loop

// sum the values of the column you need
$sum = array_sum(array_column($data, 'consumption'));

echo $sum; //would be the sum of all the values in consumption

Upvotes: 1

Related Questions