I have problem connected with function returning array from sql query. The problem is that I want to return category as string and amount as float. I think the best solution is to set in while loop to write that i want category as string and amount as float. But I don't know which function can I use to make this?
I was thinking to write something like this in while loop
while (($row = $stmt->fetch(PDO::FETCH_ASSOC)))
{
$data[] = [(string)$row['Category'],(float)$row['Amount']];
}
But there is no result, that I expected.
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;
}
Finally I wanted to achieve Array for google charts like this one:
$chartIncomesArray = Income::convertDataToChartForm($incomesArray);
json_encode($chartIncomesArray) =
['Category']['Amount']
['wynagrodzenie'][12.00]
['odsetki'][50.00]
etc.
Can anybody help me with this?
I solved my problem, deleting convertDataToChartForm($data) and changing getPieChartIncomes function to this:
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);
$i = 1;
$stmt->execute();
$tablica = array();
while (($row = $stmt->fetch(PDO::FETCH_ASSOC)))
{
$firstLine = true;
if ($firstLine)
{
$tablica[0] = array_keys($row);
$firstLine = false;
}
$category = $row['Category'];
$amount = $row['Amount'];
$tablica[$i]=array(strval($category),floatval($amount));
$i++;
}
return $tablica;
}
Thanks to while loop like now i can get table, where array keys are strings and another rows are: category as string and amount as int like this
['Category']['Amount']
['wynagrodzenie'][12.00]
['odsetki'][50.00]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.