MySQL to JSON, how to get the right format? - php

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.

Related

Populate PHP associative array using loop with mysql data

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.

how to solve Array merge for json in this example?

I parse Excel sheet and get this JSON:
[
{
"A":"Samsung",
"Groupe":{
"F":"TV",
"D":"HDR"
}
},
{
"A":null,
"Groupe":{
"F":null,
"D":null
}
},
{
"A":"Sony",
"Groupe":{
"F":"T.V",
"D":"LCD"
}
},
{
"A":"Sony",
"Groupe":{
"F":"PS4",
"D":"Pro edition"
}
},
{
"A":"Sony",
"Groupe":{
"F":"Smart Phone",
"D":"Quad core"
}
}
]
Php code:
$data = [];
for ($row = 15; $row <= 25; $row++) {
$data[] = [
'A' => $worksheet->getCell('A'.$row)->getValue(),
'Groupe' => [
'F' => $worksheet->getCell('F'.$row)->getValue(),
'D' => $worksheet->getCell('D'.$row)->getValue()
]
];
}
How can I organize(sort) json depending on "A"?
I tried this but I still couldn't merge "Groupe" for same "A" together:
Take away NULL colomns.
Create a copy of the Array.
Regroup fields for same element in the new Array(this didnt work)
Code:
$data1 = [];
for ($l = 0; $l < count($data); $l++){
$data1[$l] = $data[$l];
}
for ($j = 0; $j < count($data); $j++) {
if($data[$j]['A'] != NULL){
if($data[$j]['A'] !== $data[$j+1]['A']){
$data1[$j] = $data[$j];
}
else{
$data1[$j]['A']= $data[$j]['A'];
$data1[$j]['Groupe']= array_merge($data[$j]['Groupe'], $data[$j+1]['Groupe']);
}
}
}
EDIT:
The result that I'm getting for $data1 is exactly the same as the input JSON(except that NULL was deleted), so it looks like merge Array didnt work and what I need is:
[
{
"A":"Samsung",
"Groupe":{
"F":"TV",
"D":"HDR"
}
},
{
"A":"Sony",
"Groupe": [{
"F":"T.V",
"D":"LCD"
},{
"F":"PS4",
"D":"Pro edition"
}, {"F":"Smart Phone",
"D":"Quad core"
}]
}]
Plus it's showing me this :
Notice: Undefined offset: 11 in C:\xampp\htdocs\phptoexcel.php on line
43
Line 43: if($data[$j]['A'] !== $data[$j+1]['A']){
Use the A value as key in $data, so you can group by it:
$data = [];
for ($row = 15; $row <= 25; $row++) {
//get A value, skip if A = NULL
$a = $worksheet->getCell('A'.$row)->getValue(),
if($a===NULL)continue;
//get F and D VALUE, skip if one of them = NULL
$f = $worksheet->getCell('F'.$row)->getValue();
$d = $worksheet->getCell('D'.$row)->getValue();
if($f===null || $d===null)continue;
//test if A is a key in $data. If not, create
if(!array_key_exist( $a, $data ){
$data[$a]=[
'A'=>$a,
'Groupe'=>[]
];
}
//Put F and D in a new array in Groupe
$data[$a]['Groupe'][]=["F"=>$f,"D"=>$d];
}
You will end up with:
$data=>
[ "Samsung" =>[ "A" => "Samsung",
"Groupe" => [ 0 =>[ "F" => "TV",
"D" => "HDR"
]
]
],
"Sony" => [ "A" => "Sony",
"Groupe" => [ 0 =>[ "F":"TV",
"D":"HDR"
],
1 =>[ "F":"T.V",
"D":"LCD"
],
2 =>[ "F":"PS4",
"D":"Pro edition"
],
3 =>[ "F":"Smart Phone",
"D":"Quad core"
],
]
]
Try This
$arrUnique = array();
$result = array();
$i=0;
foreach($data as $value){
if($value['A']!=null){
$data1 = [];
$intID = $value['A'];
if( in_array( $intID, $arrUnique ) ) {
$key = array_search ($intID, $arrUnique);
$result[$key]['Groupe'][] = $value['Groupe'];
}else{
$data1['A'] = $value['A'];
$data1['Groupe'][] = $value['Groupe'];
$result[$i]=$data1;
$arrUnique[]=$value['A'];
$i++;
}
}
}
I usually don't perform JSON to JSON transformation using PHP but using jq command line utility.
Given your input JSON file, you can use this jq filter:
jq '[[sort_by(.A)|.[]|select(.A!=null)]|group_by(.A)|.[]as $i|{A:$i[].A,Groupe:$i|map(.Groupe)}]|unique' file
[
{
"A": "Samsung",
"Groupe": [
{
"F": "TV",
"D": "HDR"
}
]
},
{
"A": "Sony",
"Groupe": [
{
"F": "T.V",
"D": "LCD"
},
{
"F": "PS4",
"D": "Pro edition"
},
{
"F": "Smart Phone",
"D": "Quad core"
}
]
}
]

how to convert for loop results in json

I Want to convert this php results in to JSON.
for ($i = 0; $i < (count($getnodays)); $i++)
{
$category = $getctgry[$i];
$Priority = $getpriotity[$i];
$NoOfDays = $getnodays[$i];
$StDate = $date1[$i];
$EdDate = $date2[$i];
}
Results Required to be in :
{
"Category": "Category",
"Priority": "Priority1",
"StDate": "1/1/2016",
"EdDate": "5/1/2018"
},{
"Category": "Category",
"Priority": "Priority1",
"StDate": "1/1/2016",
"EdDate": "5/1/2018"
},{
"Category": "Category",
"Priority": "Priority1",
"StDate": "1/1/2016",
"EdDate": "5/1/2018"
}
In your loop, create a new array occurance each iteration.
Then use json_encode() to turn that array into a valid JSON string.
$json = [];
for ($i = 0; $i < (count($getnodays)); $i++) {
$json[] = ['Category' => $getctgry[$i],
'Priority' => $getpriotity[$i],
'NoOfDays' => $getnodays[$i],
'StDate' => $date1[$i],
'EdDate' => $date2[$i],
];
}
echo json_encode($json);

How to get json format below in php

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.

Parse the items in an multidimentional array php

I am creating an e-commerce website where I have to give the categories that a shop has in a particular array . Currently the data getting retrieved from a mysql table contains the same category id's in different array items if the array has different subcategory , I have to gather the same category id's in the same array and for subcategories create a nested array . The code is on laravel 4.2 . Here is the format of data coming right now ,
"data": [
{
"id": 1,
"name": "Fruits",
"sub_category_names": [
"Dairy Whiteners"
],
"total_items": 69
},
{
"id": 1,
"name": "Fruits",
"sub_category_names": [
"Tea & Coffee"
],
"total_items": 69
},
{
"id": 1,
"name": "Fruits",
"sub_category_names": [
"Concentrates - Tang etc"
],
"total_items": 69
},
{
"id": 2,
"name": "Beverages",
"sub_category_names": [
"Tea & Coffee"
],
"total_items": 28
},
{
"id": 2,
"name": "Beverages",
"sub_category_names": [
"Concentrates - Tang etc"
],
"total_items": 28
}
]
Here is what I need ,
"data": [
{
"id": 1,
"name": "Fruits",
"sub_category_names": [
"Dairy Whiteners" , "Concentrates - Tang etc" , "Tea & Coffee"
],
"total_items": 69
} ,
{
"id": 2,
"name": "Beverages",
"sub_category_names": [
"Tea & Coffee" , "Concentrates - Tang etc"
],
"total_items": 28
}
]
The code I wrote for the above ,
// For the current categories create a common array for subcategories for same categories
$filteringSelectedCategories = [];
$subCategoriesNamesLocal = [];
$innerIndex = 0;
for ($i = 0; $i < count($selectedCategories); $i++) {
// to prevent undefined offset error
if (!isset($selectedCategories[$i + 1])) {
continue ;
// if 6 don't exist then deal with 5
}
// if the id of two items is same then push that sub category name in the same array
if ($selectedCategories[$i]['id'] === $selectedCategories[$i + 1]['id']) {
array_push($subCategoriesNamesLocal, $selectedCategories[$i]['sub_category_names']);
}
// if the id is different then push the array values with the sub category name in an array
else {
$filteringSelectedCategories[$innerIndex]['id'] = $selectedCategories[$i]['id'];
$filteringSelectedCategories[$innerIndex]['name'] = $selectedCategories[$i]['name'];
$filteringSelectedCategories[$innerIndex]['sub_category_names'] = $subCategoriesNamesLocal;
$filteringSelectedCategories[$innerIndex]['total_items'] = $selectedCategories[$i]['total_items'];
// nullify the array after assigning the value
$subCategoriesNamesLocal = [];
// increment the new array index
$innerIndex = $innerIndex + 1;
}
}
Here is the output I get from the above ,
"data": [
{
"id": 1,
"name": "Fruits",
"sub_category_names": [
[
"Dairy Whiteners"
],
[
"Tea & Coffee"
]
],
"total_items": 69
}
]
I'm not entirely sure I see what offset error could occur but I believe you could easily get away with;
foreach ($selectedCategories as $key => $data) {
$newKey = $data['id'];
$filteringSelectedCategories[$newKey]['id'] = $data['id'];
$filteringSelectedCategories[$newKey]['name'] = $data['name'];
$filteringSelectedCategories[$newKey]['sub_category_names'][] = $data['sub_category_names'];
$filteringSelectedCategories[$newKey]['total_items'] = $data['total_items'];
}
You can not make an array push directly in $subCategoriesNamesLocal because you are nesting arrays. Make an array outside and then concatenate it to the field.
Try this:
// For the current categories create a common array for subcategories for same categories
$filteringSelectedCategories = [];
$subCategoriesNamesLocal = [];
$innerIndex = 0;
for ($i = 0; $i < count($selectedCategories); $i++) {
// to prevent undefined offset error
if (!isset($selectedCategories[$i + 1])) {
continue ;
// if 6 don't exist then deal with 5
}
// if the id of two items is same then push that sub category name in the same array
if ($selectedCategories[$i]['id'] === $selectedCategories[$i + 1]['id']) {
array_push($subCategoriesNamesLocal, $selectedCategories[$i]['sub_category_names']);
}
// if the id is different then push the array values with the sub category name in an array
else {
$filteringSelectedCategories[$innerIndex]['id'] = $selectedCategories[$i]['id'];
$filteringSelectedCategories[$innerIndex]['name'] = $selectedCategories[$i]['name'];
$filteringSelectedCategories[$innerIndex]['sub_category_names'] = '"' . implode('","', $subCategoriesNamesLocal) . '"';
}
$filteringSelectedCategories[$innerIndex]['total_items'] = $selectedCategories[$i]['total_items'];
// nullify the array after assigning the value
$subCategoriesNamesLocal = [];
// increment the new array index
$innerIndex = $innerIndex + 1;
}
}

Categories