PHP json format encoding - javascript

I've got the following code:
$data = array(
"1421852400000" => "100",
"1421856000000" => "110",
);
$newData = json_encode($data);
echo $newData;
This is what comes out (using the PHP code above)
{"1421852400000":"100","1421856000000":"110"}
But what I really need is the array in this format:
[
[1421852400000, 100],
[1421856000000, 110],
[1421859600000, 125]
]
Also, the first value is a timestamp (being used in Flot charts) and the second value is for the y axis of the graph.
In javascript I get these values like this:
var visit = JSON.parse(xmlhttp.responseText);
When I simply display the desired format it works, but when I try the PHP things it's giving me some odd results..
The problem is that when I use a PHP array and encode it then echo that and fetch it with Ajax and parse it with js it's not in the right format and thus it does not work..
How would I get the desired result? Thanks in advance!

This Is what you should put in the $data.
$data = array(
array("1421852400000", "100"),
array("1421856000000","110"),
);
$newData = json_encode($data);
echo $newData;
If you really need to display something similar to this:
[
[1421852400000, 100],
[1421856000000, 110],
[1421859600000, 125]
]

Change $data to something like this:
$data = array(
array(1421852400000, 100),
array(1421856000000, 110)
);

Related

Regarding Data table source data access

I have used the datatable ajax call for listing I received the below json data in ajax call:
{
"sEcho":1,
"iTotalRecords":"1",
"iTotalDisplayRecords":"1",
"aaData":[
["Demo to Mam","2"]
],
"countOfTotalRecords":2
}
How I can use the countOfTotalRecords var value on view page?
You've to decode your JSON data using json_decode, then you have an object. Looks something like this:
$json = '{"sEcho":1,"iTotalRecords":"1","iTotalDisplayRecords":"1","aaData":[["Demo to Mam","2"]],"countOfTotalRecords"
:2}';
$decode = json_decode($json);
echo $decode->countOfTotalRecords; // this will display 2, regarding your data
use the below code
$str = '{"sEcho":1,"iTotalRecords":"1","iTotalDisplayRecords":"1","aaData":[["Demo to Mam","2"]],"countOfTotalRecords":2}';
$arr = json_decode($str);
$tcount = $arr->countOfTotalRecords;
echo $tcount;

Associative php array sent via jquery returns [Object object]

I have to pass a php multidimensional array via ajax/jQuery to another php file.
I have encoded the array using
I expected theat every item in the array would have been an array itself. Instead it returns [Object object].
How can I access the data using php?
here's my code:
in the first php file:
<script type="text/javascript">
var arr_data = <?php echo json_encode($itemsData); ?>;
$("#confirmButton").click(function(){
$.post("send_test.php", {"my_array_data[]":my_array_data}, function( data ) {
alert(data);
});
});
</script>
the other php file:
<?php
$my_array_data = $_POST['my_array_data'];
?>
if I try to retrieve the first row ($my_array_data[0]) I get [Object object]
I just want to access to $my_array_data[0]['category'] etc.
A couple of errors here:
the data you are passing to ajax has an incorrect key using brackets[]
you are not passing the correct object through ajax since my_array_data is never defined
redo your code like this:
PHP
$itemsData = array(
array(
"test" => 30,
"test2" => 10,
),
array(
"test" => 90,
"test2" => 50,
)
);
JS
var arr_data = <?php echo json_encode($itemsData); ?>;
$("#confirmButton").click(function () {
$.post("send_test.php", {my_array_data: arr_data}, function (data) {
console.log(data);
});
});
Then in send_test.php
$data = $_POST['my_array_data'];
print_r($data);
Result:
Array
(
[0] => stdClass Object
(
[test] => 30
[test2] => 10
)
[1] => stdClass Object
(
[test] => 90
[test2] => 50
)
)
You're putting json-encoded data into the arr_data javascript variable - however you don't appear to be sending that to the other php file.
In the other php file, try using json_decode on the data you're receiving in the POST request:
$my_array_data = json_decode($_POST['my_array_data']);
Yes, as Aric says, name array consistently like this:
var my_arr_data = <?php echo json_encode($itemsData); ?>;

json string is not converting into object

Here is the server side code I am trying to send json
$x = array();
$timestamp = strtotime('22-09-2008');
$x["x"] = $timestamp;
$x["y"] = 22;
$val = '[{ "name": "weight", "dataPoints": ['.json_encode($x).'] }]';
echo json_encode($val);
So output for above code looks like
"[{ \"name\": \"weight\", \"dataPoints\": [{\"x\":1222041600,\"y\":22}] }]"
Below is the client side code I get the data via Jquery getJSON
var jqxhr = $.getJSON( "https://domain/gettracker.php?id="+id, function(data) {
console.log(data);
})
I suppose getJson converts json to object automatically , but it logs the raw json like below
"[ { name: "weight", dataPoints: [{"x":1222041600,"y":22}] } ]"
I tried to do json parse , but i get error.
I guess I am not sending the data properly via php.Can some one guide me ?
Your JSON string is not valid - the property names should be enclosed in double quotes - ", and you don't need to encode the string again.
$val = '[{ "name": "weight", "dataPoints": ['.json_encode($x).'] }]';
echo $val;
Or better yet, use json_encode to create the string for you:
$data = array(
'name' => 'weight',
'dataPoints' => $x
);
echo json_encode($data);

HighCharts, Json Format

So i'm attempting to use highcharts with the pie chart drilldown option.
Working with static data this is working perfectly. However, as I would like to use the Pie chart as a form of reporting, Ideally It needs to run with dynamic data.
The top level data is made up of requests. Each request is made up of subsequent tasks.
This is the php I have which retrieves the tasks and requests.
foreach($getRequests as $key=> $val){
$timeArr = explode(':', $val['duration']);
$decTime = ($timeArr[0]) + ($timeArr[1]/60); // this is purely to convert hh:mm to decimal time
$pieData['name'] = $val['name'];
$pieData['y'] = $decTime;
$pieData['drilldown'] = $key;
$pie[]=$pieData;
// This creates the first level of data which the $pie[] array gives the correct format, so when json_encode is applied, the data is usable
$getTasks = $task->getReportTasks($user, $status, $key, $dateRange, $date);
foreach($getTasks as $taskKey => $taskVal){
$pieTasks['id']=$key;
$pieTasks['name'] = "Tasks";
$timeArrTask = explode(':', $taskVal['duration']);
$decTimeTask = ($timeArrTask[0]) + ($timeArrTask[1]/60);
$pieTasks['data'] = array($taskVal['name'], $decTimeTask);
$pie2[] = $pieTasks;
}
}
However by applying the same logic to tasks and using json_encode, I end up with the following.
[
{"id":25684
,"name":"Tasks"
,"data":["test task1",3]
}
,{"id":25684
,"name":"Tasks"
,"data":["testtask2",14.383333333333]
}
,{"id":25689
,"name":"Tasks"
,"data":["testtask3",1]}
]
But the format I need is for tasks with the same request ID, the "id" field to be contained within the same data field.
Like so
[
{"id":25684
,"name":"Tasks"
,"data":[
["test task1",3]
,["testtask2",14.383333333333]
]
}
,{"id":25689
,"name":"Tasks"
,"data":[
["testtask3",1]
]
}
]
where because testtask2 has the same id, it is contained within the same data field.
I hope this makes sense and any help anyone can provide so I can structure this correctly would be greatly appreciated.
Not tested, but try to replace the last foreach with this code:
$pieTasks['id'] = $key;
$pieTasks['name'] = "Tasks";
$pieTasks['data'] = array();
foreach($getTasks as $taskKey => $taskVal){
$timeArrTask = explode(':', $taskVal['duration']);
$decTimeTask = ($timeArrTask[0]) + ($timeArrTask[1]/60);
$pieTasks['data'][] = array($taskVal['name'], $decTimeTask);
}
$pie2[] = $pieTasks;
Standart JSON parser can't parse double (14.383333333333) .
Try write in double quotes ( "14.383333333333" )

Change JSON_Encode output format (Brackets and Commas)

I have an array that is created in PHP, and then encoded into my javascript via JSON.
The Array is defined here:
$stmt -> bind_result($match_id, $hero, $mmr);
while($stmt -> fetch()){
$grapharray[] = array($hero => $mmr);
}
and JSON encoded here:
$grapharray_labelled = array(
"label" => "MMR Over time",
"data" => $grapharray
);
and here:
var graphdata = <?php echo JSON_encode($grapharray_labelled); ?>;
The output when I run my webpage is that graphdata =:
{
"label":"MMR Over time",
"data":[
{"Rubick":6524},
{"Lion":6550},
{"Magnus":6565},
{"Keeper of the Light":6566}
]
}
However I would like it to be like this:
{
"label":"MMR Over time",
"data":[
["Rubick", 6524],
["Lion", 6550],
["Magnus", 6565],
["Keeper of the Light", 6566]
]
}
Reason:
I would like to change the format because I am trying to get flot to work, and flot accepts an array of arrays as the datatype.
Otherwise: Is there a better way to transfer an array from PHP to JavaScript with my desired format?
Change this:
$grapharray[] = array($hero => $mmr);
TO:
$grapharray[] = array($hero, $mmr);

Categories

Resources