【问题标题】:failed to get values from arrays无法从数组中获取值
【发布时间】:2016-12-17 15:03:33
【问题描述】:

大师们好!在获取数组中的总和、最大值、最小值时遇到了一些问题

我的脚本是这样的;

$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],

echo array_sum(array_column($consumption, [2])); //总结第三列中的所有值

但是当我调用来总结(消耗)的 /max/min 值时 它没有任何回应。有什么遗漏吗?在这里需要一些帮助。我想要 获取 sum, max , min 消耗值。

我在 mysql set 语句中尝试了 user def var,它可以工作,但是当我使用 php 运行它时出现错误。这是我的查询 (SET @firstreading:=30089; SELECT (reading-@firstreading) AS 消费,@firstreading:=reading FROM table)。 它在 mysql 中成功,但我在使用 php 运行时在浏览器中出现错误。 error myqsl line 1 blah blah blah....(用户自己定义 var)

【问题讨论】:

  • 但是当我调用来总结(消耗)的 /max/min 值时 -> 你调用它的代码在哪里?
  • 抱歉,它已被删除。它应该在输出之下..顺便说一句,这里是代码 echo array_sum(array_column($consumption, [2]));
  • 您能否编辑问题并将代码插入正确的位置?
  • 已编辑,请见上
  • 是 $consumption 数组吗?也许我错了,但你这里有字符串?

标签: php mysql


【解决方案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

【讨论】:

  • 它没有回应。之前已经尝试过这种方法,但没有
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多