Brooke Smith
Brooke Smith

Reputation: 19

how can I modify my JSON result?

when I return my array by I got [{"product":"TEST_1","best_selling_product":"305"},{"product":"IPHONE 4S","best_selling_product":"108"}] , but Highcharts dont let me use string as value then how can I change it to int or float? my backend function is this

function best_selling_product(){
        $sql = "SELECT product,SUM(sale_detail.amount) AS best_selling_product FROM sale_detail INNER JOIN product ON sale_detail.idproduct = product.idproduct GROUP BY sale_detail.idproduct ORDER BY SUM(sale_detail.amount) DESC LIMIT 0,5"; 
        $result = $this->conexion->conexion->query($sql);
        $array = array();
        while($record = $result->fetch_array(MYSQLI_ASSOC)){
            $array[] = $record;
        }
        return $array;
        $this->conexion->cerrar();
    }

Upvotes: 1

Views: 42

Answers (2)

Sebastian Bochan
Sebastian Bochan

Reputation: 37588

In the json_encode() function, set the JSON_NUMERIC_CHECK flag.

Upvotes: 3

Tristan
Tristan

Reputation: 3321

You can either use CAST in the mysql query, or process the data in php using floatval() or intval().

For example in the mysql query:

SELECT CAST(SUM(sale_detail.amount) as UNSIGNED) AS best_selling_product FROM ...

OR with php:

while($record = $result->fetch_array(MYSQLI_ASSOC)){
    $record['best_selling_product'] = floatval($record['best_selling_product']);
    $array[] = $record;
}

Upvotes: 2

Related Questions