【发布时间】:2022-01-08 12:28:54
【问题描述】:
我遇到了与从 sql 查询返回数组的函数有关的问题。问题是我想将类别作为字符串返回,将金额作为浮点数返回。我认为最好的解决方案是在while循环中设置我希望类别为字符串,数量为浮点数。但是我不知道我可以用哪个函数来做这个?
我想在while循环中写这样的东西
while (($row = $stmt->fetch(PDO::FETCH_ASSOC)))
{
$data[] = [(string)$row['Category'],(float)$row['Amount']];
}
但没有我预期的结果。
public static function getPieChartIncomes()
{
if (empty(Income::$this->errors)) {
$sql = "SELECT income_category_assigned_to_user_id as Category, SUM(amount) as Amount FROM incomes WHERE user_id = :userId GROUP BY income_category_assigned_to_user_id ORDER BY SUM(amount) DESC ";
$db = static::getDB();
$stmt = $db->prepare($sql);
$stmt->bindValue(':userId', $_SESSION['user_id'], PDO::PARAM_INT);
$stmt->execute();
$data=array();
while (($row = $stmt->fetch(PDO::FETCH_ASSOC)))
{
$data[] = $row;
}
return $data;
}
return false;
}
public static function convertDataToChartForm($data)
{
$newData = array();
$firstLine = true;
foreach ($data as $dataRow)
{
if ($firstLine)
{
$newData[] = array_keys($dataRow);
$firstLine = false;
}
$newData[] = array_values($dataRow);
}
return $newData;
}
最后我想为像这样的谷歌图表实现数组:
$chartIncomesArray = Income::convertDataToChartForm($incomesArray);
json_encode($chartIncomesArray) =
['Category']['Amount']
['wynagrodzenie'][12.00]
['odsetki'][50.00]
etc.
有人可以帮我吗?
【问题讨论】:
-
看来您的问题不在代码中。看起来数据库中的数据不是浮动的。
-
你能举例说明你存储在数据库中的实际值吗?当你不“转换”它时,你现在得到的结果到底是什么? (关于转换类别的部分甚至应该产生什么意义?为什么
wynagrodzenie需要转换为字符串值 - 如果不是字符串值,它可能是什么else?)
标签: php model-view-controller google-visualization