Reputation: 67
I am trying to get my JSON encoded array formatted properly. Here is my PHP MySQL Query:
$query = "SELECT date, value1, value2
FROM testdata
ORDER BY date ASC";
$result = mysql_query($query);
$myChartData = array();
while($row = mysql_fetch_assoc($result)){
$myChartData[] = $row;
}
<script type="text/javascript">
var chartData = <?php echo json_encode($myChartData); ?>;
From the console, the object looks like this:
[Object { date="2011-02-23", value1="133034", value2="12105.78"},
Object { date="2011-02-24", value1="122290", value2="12068.50"},
Object { date="2011-03-08", value1="453142", value2="12214.38"}]
The quotation marks around the date stays, but the ones on value1 and value2 need to be stripped out.
Self-teaching noob at all of this...Thanks for your help!
Upvotes: 3
Views: 2290
Reputation: 51
JSON_NUMERIC_CHECK will remove the double quotes from the numeric values in your JSON string.
Example: https://3v4l.org/ip6GN
$v = json_decode('[{"id":"1","name":"Jack","username":"Jack1","age":"23"}]');
echo 'Normal:' . \PHP_EOL;
echo json_encode($v) . \PHP_EOL . \PHP_EOL;
echo 'Numeric Check:' . \PHP_EOL;
echo json_encode($v, JSON_NUMERIC_CHECK). \PHP_EOL .
Numeric Check: {"id":1,"name":"Jack","username":"Jack1","age":23}
Upvotes: 0
Reputation: 816404
First:
The quotation marks around the date stays, but the ones on value1 and value2 need to be stripped out.
There are no quotation marks! What you see as a visual representation of the data contained in chartData
. In this case it is an array with three objects, each having three properties containing strings.
What you want is to convert some of these strings into numbers (integers, floating point).
It seems you are not storing the data correctly in your DB. If the values were numbers, they would be encoded as such.
The only reasonable solution is to fix it at that end. That means you have to define the data types of your DB fields properly.
If, for some reason, you cannot fix the DB (you should try really hard), you have the possibility to convert the strings to numbers
intval
[docs] and/or floatval
[docs]or in JavaScript with the unary plus operator [docs]:
var number = +string;
If you are new to JavaScript, you might want to read Working with Objects [MDN] first.
Upvotes: 2
Reputation: 82594
A simple javascript solution:
function formatChartData(data) {
for(var i = 0, length = data.length; i < length; i++) {
data[i].value1 = parseInt(data[i].value1, 10);
data[i].value2 = parseFloat(data[i].value2);
}
return data;
}
var chartData = formatChartData(<?php echo json_encode($myChartData); ?>);
Upvotes: 1