2016-12-17 12 views
2

良い日の達人!配列の合計値、最大値、最小値を得るためのいくつかの問題があります配列から値を取得できませんでした

私のスクリプトはこのようになります。

$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."],"; 

このようなものが得られます。

['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], 

エコーarray_sum(array_column($消費、[2]))。 //第3列のすべての値を集計します

しかし、私が(消費) の合計/最大値/最小値を呼び出すとき、何もエコーしません。何か不足していますか?ここで何か助けが必要です。私は したい消費量の合計、最大、最小値を取得します。

私はmysqlのset文でユーザーdef varを試してみましたが、PHPで実行するとエラーが発生します。ここで私のクエリです(SET @firstreading:= 30089; SELECT(reading- @ firstreading)AS消費、@firstreading:= FROMテーブルの読み込み)。 それはmysqlで成功しますが、私はPHPで動作するブラウザでエラーが発生しています。エラーmyqslライン1何とか何とか何とか....(ユーザーがVAR自体の定義)

+1

_but私は合計すると呼ばれます/消費量の最大値/最小値_ - >これはどこのコードですか? – jitendrapurohit

+0

申し訳ありませんが削除されました。その出力の下にあるはずです..ところで、コードをエコーarray_sum(array_column($消費、[2])); –

+0

質問を編集して、適切な場所にコードを挿入してください。 – jitendrapurohit

答えて

1

私はあなたが再書き込みこのする必要があると思うし、それを行うようなもの -

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 
+0

何もエコーしません。以前はこのアプローチを試していましたが、何も –

関連する問題