I'm on this trouble since a week from now. I've read a lot of topics here on stackoverflow and on various blogs that I googled but I still need help from you on solving this issue. For many of you this is a dumb question, so I apologize since now for my not so big knowledge of php/javascript languages but I'm in a learning phase and I'm sure you will support me during this formation path.
My main problem is to convert a json_encode output array into something that I can use into Flot that works in javascript.
My current PHP code is the following:
$csv_is_a = str_getcsv(file_get_contents('csv/IS_A.csv'));
$csv_is_q = str_getcsv(file_get_contents('csv/IS_Q.csv'));
for ($i=1, $k=12; $i<12, $k<22; $i++, $k++) {
$JsonArray[] = array( $csv_is_a[$i] => $csv_is_a[$k]);
}
echo '<pre>';
print_r( $JsonArray );
echo '</pre>';
The output of this code is:
Array (
[0] => Array
(
[2005-09] => 13931
)
[1] => Array
(
[2006-09] => 19315
)
[2] => Array
(
[2007-09] => 24006
)
[3] => Array
(
[2008-09] => 32479
)
[4] => Array
(
[2009-09] => 42905
)
[5] => Array
(
[2010-09] => 65225
)
[6] => Array
(
[2011-09] => 108249
)
[7] => Array
(
[2012-09] => 156508
)
[8] => Array
(
[2013-09] => 170910
)
[9] => Array
(
[2014-09] => 182795
)
)
Now I apply the json_encode:
$csv_enc = json_encode( $JsonArray );
The output of this is:
[{"2005-09":"13931"},{"2006-09":"19315"},{"2007-09":"24006"},{"2008-09":"32479"},{"2009-09":"42905"},{"2010-09":"65225"},{"2011-09":"108249"},{"2012-09":"156508"},{"2013-09":"170910"},{"2014-09":"182795"}]
But what I want is this:
[[2005-09, 13931],[2006-09, 19315],[2007-09, 24006],[2008-09, 32479],[2009-09, 42905],[2010-09, 65225],[2011-09, 108249],[2012-09, 156508],[2013-09, 170910],[2014-09, 182795]]
In the javascript section of the code I tried to use the JSON.parse() in this way:
<script type="text/javascript">
var data = JSON.parse(<?php echo $csv_enc ;?>);
$(document).ready(function() {
$.plot($("#placeholder"), [data]);
});
</script>
but it doesn't work. If I substitute the "JSON.parse()" with a bidimensional object, the script works without problems. So, the trouble should be just in that part of the code. What's the issue in your opinions? Thanks for your support.
UPDATE:
I've used the code suggested by @callback, but it doesn't work. Here it is:
<script type="text/javascript">
var theArray = <?php echo $csv_enc; ?>, multiArray = [];
for(var i = 0 ; i< theArray.length ; i++){
var obj = theArray[i];
for( k in obj) {
multiArray[i] = [k, parseInt(obj[k])];
}
}
console.log(multiArray)
$(document).ready(function() {
$.plot($("#placeholder"), [multiArray]);
});
</script>
The console.log doesn't print anything...