简体   繁体   中英

Formatting an array as JSON for input into Google Charts API?

Noticed that integer values need to be integers in the json , however I am using strings.

The raw array is:

   '[{"sctr":"Asset Managers","amount":"1586500"},{"sctr":"Auto 
    Parts","amount":"1618000"},{"sctr":"Business Support 
    Services","amount":"1012020"},{"sctr":"Coal","amount":"1043550"},
    {"sctr":"Consumer Finance","amount":"2285000"},...

I then use the following code, to remove keys sctr and amount :

        $sector_final = array();
        array_push($sector_final, array("Sector", "Amount"));
        foreach( $sector_data as $row){
            array_push($sector_final, array_values($row));
        }
        var_dump(json_encode($sector_final));'

Giving:

'[["Sector","Amount"],["Asset Managers","1586500"],["Auto
 Parts","1618000"],["Business Support Services","1012020"],
["Coal","1043550"],["Consumer Finance","2285000"],

However the amounts must not be in quotation marks for the Google Chart Api to work.

How can I do that, also is there a more efficient way of removing the keys for the json?

Try to cast that particular element into int before feeding/puhsing it:

$sector_final = array();
array_push($sector_final, array("Sector", "Amount"));
foreach( $sector_data as $row){
    $row['amount'] = (int) $row['amount']; // cast it
    array_push($sector_final, array_values($row));
}
$sector_final = array();

    //array_push($sector_final, array("Sector", "Amount"));
    foreach( $sector_data as $row){

        $final = array("Sector" => "' . $row['sector'] . '",
                       "Amount" => $row['amount']);

        array_push($sector_final, $final);
    }
    var_dump(json_encode($sector_final));

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM