I'm quite new to php and don't actually know if this is possible
Im currently outputting JSON code with php using the following code
echo json_encode($output, JSON_NUMERIC_CHECK);
But what I want to do is have the above data inside a variable.
I tried
$JSONDATAX = json_encode($output, JSON_NUMERIC_CHECK);
But it doesn't seem to like it when I call $JSONDATAX.
The original echo way works completely fine.
edit ........
$lrs = CDB::ExecuteQuery($sql);
if($lrs) {
$jsonData = convert($lrs);
}
function convert($lrs) {
$intermediate = array();
while ($vals = CDB::GetAssoc($lrs)) {
$key = $vals['POS'];
$x = $vals['CODE'];
$y = $vals['COUNT'];
$intermediate[$key][] = array('x' => $x, 'y' => $y);
}
$output = array();
foreach($intermediate as $key => $values) {
$output[] = array(
"key" => $key,
'values' => $values
);
}
$data1 = json_encode($output, JSON_NUMERIC_CHECK);
}
?>
<script>
var negative_test_data = <?php echo $data1; ?>;
var chart;
nv.addGraph(function() {
chart = nv.models.multiBarChart()
.color(d3.scale.category10().range())
.rotateLabels(0) //Angle to rotate x-axis labels.
.transitionDuration(300)
.showControls(true) //Allow user to switch between 'Grouped' and 'Stacked' mode.
.groupSpacing(0.24) //Distance between each group of bars.
;
As you can see, I am using php just after var negative_test_data , but it doesn't produce anything.
In your edited example, $data is a local variable inside the convert function, so it cannot be accessed outside that function. the result of json_encode should be returned:
$data1 = json_encode($output, JSON_NUMERIC_CHECK);
should be
return json_encode($output, JSON_NUMERIC_CHECK);
Then, the result of the convert function can be echoed:
var negative_test_data = <?php echo $data1; ?>;
should be
var negative_test_data = <?php echo convert($lrs); ?>;
(There should probably be a an additional if around that whole part, depending on what you want to happen when $lrs does not evaluate to true)
This should be all you really need:
$phpvar = json_encode($output);
echo "<script>var negative_test_data = {$phpvar};</script>";
Related
I want to save my data from foreach as "name data": value to variable ChartVal, but I don't how to do it I'm still learning.
<?php
$nim = $this->uri->segment(3);
$chart = $this->modelpenilaian->getchart($nim);
foreach ($chart as $ca) {
$a[i] = "$ca->name": $ca->nilai;
} //I know this is wrong, I just don't know the right one
?>
<script>
var chartVals = <?php echo json_encode($a[i])?>;
//I want to save to variable chartVals
$(function(){
$('#chart').radarChart({
size: [500, 400],
step: 1,
title: " ",
values: {
//"chartVals": chartVals
//then send it to jquery value
chartVals
},
showAxisLabels: true
});
});
You most likely need to set the key of $a array to the name you want ($ca->name in your case)....
$a=array();
foreach ($chart as $ca) {
$a[$ca->name] = $ca->nilai;
}
and then
echo json_encode($a);
When adding the data to the chart, you need to use
values: chartVals,
Is this what you're looking for?
foreach ($chart as $ca) {
$a[$ca->name] = $ca->nilai;
}
That gives you an array of key:value pairs. To turn it into JSON you would:
$myJSON = json_encode($a);
$markers =array();
$getmap = $mysqli->query("SELECT `desc`,`lat`,`long` FROM map");
$i=0;
$markers = $getmap->fetch_all(MYSQLI_ASSOC);
echo $markers[1]["desc"];
echo $markers;
$markers = json_encode($markers);
How is it possible such that these will flow properly and it will be read by the JS?
var position = (markers[i][lat], markers[i][long]);
Please try this way:
Hopefully it will help:
foreach($markers as $i=>$arrMarkes)
{
$finalArray[$i] = $arrMarkes;
}
echo json_encode($finalArray);
I'm currently working to retrieve some data for which I want to use a FLOT line chart.
At present, this is how I am creating the array by getting data from the MYSQL database:
$data = array("label" => $title);
while($row = $query->fetch()) {
$data['data'][] = array($row[3], $row[2]);
}
$json = json_encode($data, JSON_NUMERIC_CHECK);
echo $json;
The above code output the following array (Based on the data from the Database):
{"label":"hosting","data":[[2,"06\/07\/2014"],[7,"09\/07\/2014"]]}
This is what I want, however I need to somehow change the formatting of the array so that it is correctly formatted for the FLOT charts.
How would I got about changing the array from this:
{"label":"hosting","data":[[2,"09\/07\/2014"],[2,"09\/07\/2014"]]}
To this:
{label: 'hosting', data: [[2,09\/07\/2014], [2,09\/07\/2014]]}
Using JQuery try this,
<script type="text/javascript">
var obj = jQuery.parseJSON ( ' + <?php echo $json; ?> + ' );
</script>
try doing this
$data = array(label => $title, data => array());
while($row = $query->fetch()) {
$data[data][] = array($row[3], $row[2]);
}
instead
$data = array("label" => $title);
while($row = $query->fetch()) {
$data['data'][] = array($row[3], $row[2]);
}
I have a problem with my javascript array. Bellow my code:
$namen = array();
$mainimg = array();
$sql1 = mysql_query("SELECT * FROM image WHERE id = ".$id.";");
echo "<div class='normal'>";
while($row = mysql_fetch_array($sql1))
{
$namen[] = $row['bild'];
$mainimg[] = $row['mainimg'];
$number_array = count($namen);
?>
<script type='text/javascript'>
<?php
for($a=1; $a <= count($namen); $a++){
$php_array = array($a => $row['bild']);
$js_array = json_encode($php_array);
echo "var javascript_array = ". $js_array . ";\n";
echo "document.write(javascript_array + '<br />');";
}
?>
</script>
}
Now I get [object][Object] in the browser, but I wanted to printout the elements, the name of the pictures. What can I do?
Thanks for your help in advance.
Regards, Yanick
You're trying to print a Object as a string. What you need to do is to access your properties directly from the object.
<script>
<?php $data = array('foo' => 'bar'); ?>
var my_js_var = <?php echo json_encode($data); ?>;
</script>
With this script, you can access your values like this:
document.write(my_js_var.foo); // writes 'bar'
You'll need to loop through the array and output the fields you want for each item. You're currently printing out the string version of an object in JavaScript, which is always [object Object].
I want to get json with php encode function like the following
<?php
require "../classes/database.php";
$database = new database();
header("content-type: application/json");
$result = $database->get_by_name($_POST['q']); //$_POST['searchValue']
echo '{"results":[';
if($result)
{
$i = 1;
while($row = mysql_fetch_array($result))
{
if(count($row) > 1)
{
echo json_encode(array('id'=>$i, 'name' => $row['name']));
echo ",";
}
else
{
echo json_encode(array('id'=>$i, 'name' => $row['name']));
}
$i++;
}
}
else
{
$value = "FALSE";
echo json_encode(array('id'=>1, 'name' => "")); // output the json code
}
echo "]}";
i want the output json to be something like that
{"results":[{"id":1,"name":"name1"},{"id":2,"name":"name2"}]}
but the output json is look like the following
{"results":[{"id":1,"name":"name1"},{"id":2,"name":"name2"},]}
As you realize that there is comma at the end, i want to remove it so it can be right json syntax, if i removed the echo ","; when there's more than one result the json will generate like this {"results":[{"id":1,"name":"name1"}{"id":2,"name":"name2"}]} and that syntax is wrong too
Hope that everybody got what i mean here, any ideas would be appreciated
If I were you, I would not json_encode each individual array, but merge the arrays together and then json_encode the merged array at the end. Below is an example using 5.4's short array syntax:
$out = [];
while(...) {
$out[] = [ 'id' => $i, 'name' => $row['name'] ];
}
echo json_encode($out);
Do the json_encoding as the LAST step. Build your data structure purely in PHP, then encode that structure at the end. Doing intermediate encodings means you're basically building your own json string, which is always going to be tricky and most likely "broken".
$data = array();
while ($row = mysql_fetch_array($result)) {
$data[] = array('id'=>$i, 'name' => $row['name']);
}
echo json_encode($data);
build it all into an array first, then encode the whole thing in one go:
$outputdata = array();
while($row = mysql_fetch_array($result)) {
$outputdata[] = $row;
}
echo json_encode($outputdata);