PHP/JSON Array Output - php

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]);
}

Related

output an array using PHP

I have the following PHP code:
while($row = mysqli_fetch_array($query))
{
$data = $row['name'];
}
I fetch all the data with the column name "name" in database. How can I output it like this?
["John", "Doe", "Deer"]
You have to make $data as array type variable.
while($row = mysqli_fetch_array($query))
{
$data[] = $row['name'];
}
print_r($data); // required output
while($row = mysqli_fetch_array($query))
{
$data[] = $row['name'];
}
print_r($data); // output key wise display like
Array ( [0] => John [1] => Doe ) etc.
But output as you suggestion then just add json_encode()
print_r(json_encode($data)); // output like
["John", "Doe", "Deer"]
$data = [];
while($row = mysqli_fetch_array($query))
{
$data = $row['name'];
}
echo json_encode($data); // or you can use print_r for debugging.
You need to use json_encode() method to your array to be accepted in your jquery. Rearrange the code like following..
$data = array();
while($row = mysqli_fetch_array($query))
{
$data[] = $row['name'];
}
$new_array = json_encode($data);
echo $new_array; // use 'echo' to print. The json_encode() convert $data array to string.

Send json data into a php variable to be used in javascript

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>";

How can I format my JSON in this way?

I'm trying to output JSON in this format:
[{"name":"venue 1"}, {"name":"venue 2"}, {"name":"venue 3"}]
But it's currently coming out like this:
{"name":"venue 1"}{"name":"venue 2"}{"name":"venue 3"}
Here is my code:
query = "SELECT * FROM venues";
$result = mysqli_query($con, $query);
while ($row = mysqli_fetch_array($result, MYSQLI_BOTH)) {
$arr = array(
'name'=> $row['name']
);
print json_encode($arr);
What do I need to change?
Add $arr[] intead of $arr
while ($row = mysqli_fetch_array($result, MYSQLI_BOTH)) {
$arr[] = array('name'=> $row['name'] );
}
echo json_encode($arr);
Try this:
$arr[] = array(
'name'=> $row['name']
);
Simply make an array like
$array[]["name"]="value1";
$array[]["name"]="value2";
$array[]["name"]="value3";
echo json_encode($array);
you will get the json data as:
[{"name":"value1"},{"name":"value2"},{"name":"value3"}]
which you wants. You have to make the array using looping statements according to your need.

Pulling data from MySQL into json array

I'm trying to pull data from my database using json in php. I have a few elements I need to specific then to post them on a page.
I want to "fetch" the data from mysql and return it to a json_encode. How can I do this using the SELECT method. Some had used PDO methods and other have used mysql_assoc, which confuses me.
For instance,
I have rows of: 'id' , 'title' , 'start', 'backgroundColor'...etc. along with a default value for all of them. ($array[] = "someValue = default")
I want it to export like so:
array(
'id' => 1,
'title' => "someTitle",
'start' => "2012-04-16",
'backgroundColor' => "blue",
'someValue' = > "default",
...
), ....
));
If anyone could help me with this with the best detail, I'd be awesome!
If you wanted to do this with PDO then here is an example:
<?php
$dbh = new PDO("mysql:host=localhost;dbname=DBNAME", $username, $password);
$sql = "SELECT `id`, `title`, `time`, `start`, `backgroundColor`
FROM my_table";
$result = $dbh->query($sql)->fetchAll(PDO::FETCH_ASSOC);
//To output as-is json data result
//header('Content-type: application/json');
//echo json_encode($result);
//Or if you need to edit/manipulate the result before output
$return = [];
foreach ($result as $row) {
$return[] = [
'id' => $row['id'],
'title' => $row['title'],
'start' => $row['start'].' '.$row['time'],
'backgroundColor' => $row['backgroundColor']
];
}
$dbh = null;
header('Content-type: application/json');
echo json_encode($return);
?>
You don't "fetch to a json array".
You fetch your database results into a PHP array, then convert that php array, AFTER THE FETCHING IS COMPLETED, to a json string.
e.g.
$data = array();
while ($row = mysql_fetch_assoc($results)) {
$data[] = $row;
}
echo json_encode($data);
You can get the result from mysql,then format it to json
$array = array();
while($row = mysqli_fetch_array($result))
{
array_push($array,$row);
}
$json_array = json_encode($array);
Please check for SELECT methods here
In general it would look like this
$data = array(); // result variable
$i=0
$query = "SELECT id,title,start,backgroundColor FROM my_table"; // query with SELECT
$result = mysql_query($query);
while($row = mysql_fetch_assoc($result)){ // iterate over results
$data['item'][$i]['id'] = $row['id']; // rest similarly
...
...
$i++;
}
header('Content-type: application/json'); // display result JSON format
echo json_encode(array(
'success' => true,
'data' => $data // this is your data variable
));

Json encode an entire mysql result set

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);

Categories