I am New to PHP I want to generate a json code like this
[{"section_name": "Section A","data": [{"value": "2"},{"value": "0"}]}, {"section_name": "Section B","data": [{"value": "1"},{"value": "0"}]}]
In this I am retrieving "section_name","value" from database.
Here the concept is get values from database to display a bar chart, based on classes and sections.
But my template I had chosen, I have to get the values(no. of students in a class & section) for individual sections, as shown in below bar chart.
My PHP Code:
$result1 = mysql_query("select class_name as label from class ") or die(mysql_error());
while($row1 = mysql_fetch_assoc($result1))
{
$rows1[] = $row1;
}
$data1 = json_encode($rows1);
$result2 = mysql_query("select s.section_name as sectionname, 'data' as data from section s") or die(mysql_error());
$result3 = mysql_query("select (select count(*)as c from student_status ss where ss.section_id=s.section_id and ss.class_id=c.class_id) as value from section s, class c order by s.section_name asc ") or die(mysql_error());
if(mysql_num_rows($result2) > 1)
{
while($row2 = mysql_fetch_assoc($result2))
{
$rows2[] = $row2;
}
$data2 = json_encode($rows2);
while($row3 = mysql_fetch_assoc($result3))
{
$rows3[] = $row3;
}
$data3 = json_encode($rows3);
}
My JSON CODE:
"categories": [
{
"category": <? echo $data1 ?>/*[
{
"label": "1"
},
{
"label": "TWO"
},
{
"label": "3"
}
]*/
}
],
"dataset": /*<? echo $data2 ?>*/[
{
"sectionname": "Section A",
"data": [
{
"value": "2" //class 1
},
{
"value": "1" //class 2
}
]
},
{
"sectionname": "Section B",
"data": [
{
"value": "" //class 1
},
{
"value": "" //class2
}
]
}
]
Hope you guys understand question.
If you are new with php, you should read array in php manual.
Then you can define an array like this
$arr = array(
array(
'section_name' => 'Section A',
'data => array(
array('value' => 2),
array('value' => 0),
)
),
)
//... other section
Then output json echo json_encode($arr);
[] is used for array and {"a": ..} for associative arrays. Combining this two together and you could easily create this json structure.
array(
array(
"section_name" => "Section A",
"data" => array(
array("value" => "2"),
array("value" => "0"),
)
),
// ...
)
Using json_encode gives you the wanted result.
Related
I'm creating simple PHP for output data to apexcharts javascript charts. To make apexcharts usable output I need to provide x and y value of the graphs as JSON. below code, I wrote to output the expected JSON.
$data_arr = array();
global $mysqli_conn;
$result = $mysqli_conn->query("sql");
$sql_out = array();
$sql_out = $result->fetch_all(MYSQLI_ASSOC);
$num_rows = mysqli_num_rows($result);
if ($num_rows < 1){
echo "zero";
}else{
foreach($sql_out as $item) {
$data_arr['x'][] = $item['time'];
$data_arr['y'][] = $item['status_code'];
}
}
$test_arr = array(
array(
"name"=>"lock",
"data"=>array($data_arr),
)
);
echo json_encode($test_arr);
my expected json output is like below
[
{
"name": "lock",
"data": [
{
"x": "2019-05-30 07:53:07",
"y": "1470"
},
{
"x": "2019-05-29 07:52:27",
"y": "1932"
}
]
}
]
But when I request data from my code what I'm getting something like this
[
{
"name": "lock",
"data": [
{
"x": [
"2019-05-30 07:53:07",
"2019-05-29 07:52:27",
"2019-05-26 15:46:56",
"2019-05-25 07:39:24"
],
"y": [
"1470",
"1932",
"1940",
"1470"
]
}
]
}
]
How can I create my expected JSON result from PHP code?.
You're creating them on a seprate space. When you declare and push them, put them on one container:
foreach ($sql_out as $item) {
$data_arr[] = array(
'x' => $item['time'],
'y' => $item['status_code']
);
}
When you do this:
$data_arr['x'][] = $item['time'];
$data_arr['y'][] = $item['status_code'];
They are on a separate containers, x and y containers, therefore you get the wrong format, like the one you showed.
When you declare them as:
$data_arr[] = array(
'x' => $item['time'],
'y' => $item['status_code']
);
You're basically tellin to push the whole sub batches but together.
I am using following code for making data coming from database as json format
public function employeeSearch()
{
$arrayOfEmployee = array();
$arrayToPush = array();
$arrayToJSON = array();
$new_item = $this->apicaller->sendRequest(array(
"controller" => "Employee",
"action" => "employeeSearch",
"searchCriteria" => "12345"
));
$arrayOfEmployee = json_decode($new_item,true);
foreach($arrayOfEmployee as $key => $employee)
{
$arrayToPush = array('data' => $employee['FullName'], 'value' => $employee['_id']['$oid']);
array_push($arrayToJSON, $arrayToPush);
}
echo json_encode($arrayToJSON);
}
The output is
[{"data":"Aasiya Rashid Khan","value":"5aa662b0d2ccda095400022f"},
{"data":"Sana Jeelani Khan","value":"5aa75d8fd2ccda0fa0006187"},
{"data":"Asad Hussain Khan","value":"5aaa51ead2ccda0860002692"},
{"data":"Ayesha Khan Khann","value":"5aab61b4d2ccda0bc400190f"},
{"data":"adhar card name","value":"5aaba0e1d2ccda0bc4001910"}
]
Now I want that json elements should look like
{
"suggestions": [
{
"value": "Guilherand-Granges",
"data": "750"
},
{
"value": "Paris 01",
"data": "750"
}
]
}
I have to implement this in jQuery autocomplete plugin...
Please help!!!
Replace the last line with
echo json_encode(["suggestions" => $arrayToJSON]);
This should result in the wanted result!
(This hold only true if you igonre the fact that the data in value and name is not the same/similar)
So, I'm using a PHP-script to output MySQL to JSON, but I'm having trouble figuring out how to output the right JSON-format.
Here's the PHP-script:
$sql_query = "SELECT * FROM DiseaseData";
$res_sql = mysql_query($sql_query) or die(mysql_error());
$arr = array();
if(mysql_num_rows($res_sql) > 0){
ini_set('memory_limit', '-1');
while($row_sql = mysql_fetch_assoc($res_sql)){
$arr[] = $row_sql;
}
$json = json_encode($arr);
$file = '../../files/json/DiseaseData.json';
file_put_contents($file, $json);
}
ini_set('memory_limit', '-1');
Here's the outputted JSON-format:
[{
"ID": "1",
"Magnitude": "0.842",
"County": "Alameda",
"Disease": "E. coli O157",
"lat": "37.7652",
"lng": "-122.242"
}, {
"ID": "2",
"Magnitude": "1.520",
"County": "Alameda",
"Disease": "HIV",
"lat": "37.7652",
"lng": "-122.242"
}]
This is the JSON-format I'd like to have it in:
{
"columns":[{
"fieldName" : "ID",
"position" : 1
},
{
"fieldName" : "Magnitude",
"position" : 2
},
{
"fieldName" : "County",
"position" : 3
},
{
"fieldName" : "Disease",
"position" : 4
},
{
"fieldName" : "lat",
"position" : 5
},
{
"fieldName" : "lng",
"position" : 6
},]
"data": [
[ 1, 0.842, "Alameda", "E. coli O157", 37.7652, -122.242],
[ 2, 1.520, "Alameda", "HIV", 37.7652, -122.242]
]
}
The solution would be like this:
Create two arrays, $columns and $data
In $columns array, store the position and the associated field name
In $data array, insert all data rows using while loop.
Finally, insert both the arrays in $result array and then apply json_enocde() on it.
Here's the code:
// your code
if(mysql_num_rows($res_sql) > 0){
$columns = $data = array();
$max_columns = mysql_num_fields($res_sql);
for($i=0; $i < $max_columns; $i++){
$columns[] = array('fieldName' => mysql_field_name($res_sql, $i), 'position' => $i+1);
}
while($row_sql = mysql_fetch_assoc($res_sql)){
$data[] = array_values($row_sql);
}
$result = array('columns' => $columns, 'data' => $data);
$json = json_encode($result);
// your code
}
Note: Don't use mysql_* functions, they are deprecated as of PHP 5.5 and are removed altogether in PHP 7.0. Use mysqli or pdo instead. And this is why you shouldn't use mysql_* functions.
I am trying to get my JSON output like this.
{"allterms":[{"group":{"Name":"Test 1"},{"group":{"Name":"Test2","Id":"298"}}]
My current code is
while($r = mysql_fetch_assoc($rs)) {
$rows['allterms']['group'][] = $r;
}
Which gives me this
{"allterms":{"group":[{"Name":"Test1", "Id":"1740"},{"Name":"Test2","Id":"631"}}]
How can I adjust my code so that each item has a parent term group.
Change the loop like so:
while($r = mysql_fetch_assoc($rs)) {
$rows['allterms'][]['group'] = $r;
}
which will generate:
array(
'allterms' => array(
0 => array(
'group' => array(...),
),
1 => array(
'group' => array(...),
)
...
)
which as json will be:
{
"allterms": [
{
"group": {
{
"Name": "Test1",
"Id": "1740"
},
{
"group": {
{
"Name": "Test2",
"Id": "631"
}
}
]
}
You could use the array_push() function from PHP.
while($r = mysql_fetch_assoc($rs)) {
array_push($rows['allterms'], $r);
}
I have two tables that I want to convert them to json like this:
[
{
"date":"2013-07-20",
"id":"123456",
"year":"2013",
"people":[
{
"name":"First",
"age":"60",
"city":"1"
},
{
"name":"second",
"age":"40",
"city":"2"
},
{
"name":"third",
"age":"36",
"city":"1"
}
]
}
]
but the result of my code is this:
[
{
"date":"2013-07-20",
"id":"123456",
"year":"2013",}
,{
"people":[
{
"name":"First",
"age":"60",
"city":"1"
},
{
"name":"second",
"age":"40",
"city":"2"
},
{
"name":"third",
"age":"36",
"city":"1"
}
]
}
]
the code creates a new object to the array "people" and I want that are in the same object
$result = mysql_query("SELECT * FROM data where id='123456'");
$fetch = mysql_query("SELECT name,age,city FROM people where id='123456'");
$json = array();
$json2['people'] = array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)){
$json[] = $row;
}
while ($row = mysql_fetch_assoc($fetch)){
$row_temp["name"]=$row["name"];
$row_temp["age"] = $row["age"];
$row_temp["city"] = $row["city"];
array_push($json2['people'],$row_temp);
}
array_push($json, $json2);
echo Json_encode($json);
How I can make the array is in the same object as the table "data"?
Many thanks
I think you may try this
$result = mysql_query("SELECT * FROM data where id='123456'");
$fetch = mysql_query("SELECT name,age,city FROM people where id='123456'");
// I think, you'll get a single row, so no need to loop
$json = mysql_fetch_array($result, MYSQL_ASSOC);
$json2 = array();
while ($row = mysql_fetch_assoc($fetch)){
$json2[] = array(
'name' => $row["name"],
'age' => $row["age"],
'city' => $row["city"]
);
}
$json['people'] = $json2;
echo json_encode($json);
Result of print_r($json) should be something like this
Array
(
[date] => 2013-07-20
[year] => 2013
[id] => 123456
[people] => Array
(
[0] => Array
(
[name] => First
[age] => 60
[city] => 1
)
[1] => Array
(
[name] => second
[age] => 40
[city] => 2
)
)
)
Result of echo json_encode($json) should be
{
"date" : "2013-07-20",
"year":"2013",
"id":"123456",
"people":
[
{
"name" : "First",
"age" : "60",
"city" : "1"
},
{
"name" : "second",
"age" : "40",
"city" : "2"
}
]
}
If you do echo json_encode(array($json)) then you will get your whole json wrapped in an array, something like this
[
{
"date" : "2013-07-20",
"year":"2013",
"id":"123456",
"people":
[
{
"name" : "First",
"age" : "60",
"city" : "1"
},
{
"name" : "second",
"age" : "40",
"city" : "2"
}
]
}
]
You were very close, but you want the People array to be a direct value of the outer array and you've wrapped it in an extra array.
Also, please note that the MySQL library you are using is deprecated. That means it will be removed from PHP in a future release. You should replace calls from the MySQL_* family of functions with either mysqli or pdo
$result = mysql_query("SELECT * FROM data where id='123456'");
$fetch = mysql_query("SELECT name,age,city FROM people where id='123456'");
$json = array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)){
$json[] = $row;
}
$json['people'] = array();
while ($row = mysql_fetch_assoc($fetch)){
$row_temp["name"]=$row["name"];
$row_temp["age"] = $row["age"];
$row_temp["city"] = $row["city"];
array_push($json['people'],$row_temp);
}
echo Json_encode($json);
You can make it work by waiting to use the key people until the very end when you join the two arrays. Up until then, just load the data into $json and $json2.
$json = array('date' => '2013', 'id' => '123456', 'year' => '2013');
$result = mysql_query("SELECT * FROM data where id='123456'");
$fetch = mysql_query("SELECT name,age,city FROM people where id='123456'");
$json = array();
$json2 = array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)){
$json[] = $row;
}
while ($row = mysql_fetch_assoc($fetch)){
$row_temp["name"]=$row["name"];
$row_temp["age"] = $row["age"];
$row_temp["city"] = $row["city"];
array_push($json2, $row_temp);
}
$json['people'] = $json2;
echo Json_encode($json);