Nested JSON file from Php and Database - php

I am working on fetching JSON file from the database, which has two table semone with attributes id, semester, cname and table courses with attributes coname and credit.
Code I am writing in php is following.
main.php
<?php
$user = "root";
$password = "";
$database = "scheduler";
$con = mysqli_connect("localhost", $user, $password, $database) or die ("Unable to connect");
$query = "SELECT semone.userid AS id, semone.semester AS semester, semone.cname AS name, courses.credit AS value
FROM semone
INNER JOIN courses
ON semone.cname = courses.coname" ;
$result = mysqli_query($con,$query)or die ("Unable to connect");
$info = array();
$test = array();
while ($row = $result->fetch_array(MYSQLI_ASSOC)) {
$row['xyz'] = array(
'name'=> $row['name'],
'value'=> $row['value']
);
$info[$row['id']]['children'][$row['semester']]['children'][]= $row['xyz'];
}
$data = json_encode(($info));
echo $data;
?>
I want to get JSON file as seen in the following code, but I am getting something like this.
output.json
{
"12345": {
"children": {
"first": {
"children": [{
"name": "C101",
"value": 100
},
{
"name": "C102",
"value": 100
}]
},
"second": {
"children": [{
"name": "C103",
"value": 50
}, {
"name": "C104",
"value": 100
}, {
"name": "C105",
"value": 100
}]
},
"third": {
"children": [{
"name": "C106",
"value": 50
}]
}
}
}
}
But this is what I am expecting.
expected.json
{
"id": 12345,
"children": [{
"semester": "first",
"children": [{
"name": "C101",
"value": 100
},
{
"name": "C102",
"value": 100
}]
}, {
"semester": "second",
"children": [{
"name": "C103",
"value": 50
}, {
"name": "C104",
"value": 100
}, {
"name": "C105",
"value": 100
}]
}, {
"semester": "third",
"children": [{
"name": "C106",
"value": 50
}]
}
}

You probably should build your array in a different way:
$info[] = array(
array('id' => $row['id']),
'children' => array(
'semester' => $row['semester'],
'children' => $row['xyz']
)
);

Related

PHP - How to change json values according to another json

I am new to PHP programming and I need your lights!
I have a JSON file like:
"data": [{
"DIAGNOSTIC_TYPE_ID": 1,
"VALUE": "288.0"
},
{
"DIAGNOSTIC_TYPE_ID": 2,
"VALUE": "-0.1"
},
{
"DIAGNOSTIC_TYPE_ID": 3,
"VALUE": "327.67"
},
{
"DIAGNOSTIC_TYPE_ID": 1,
"VALUE": "288.0"
},
{
"DIAGNOSTIC_TYPE_ID": 2,
"VALUE": "-0.1"
},
{
"DIAGNOSTIC_TYPE_ID": 3,
"VALUE": "327.67"
}]
and I have to change it using another json file which is like:
"diagnostics_keys": [
{
"ID": 1,
"type": "BTTPV",
"key": "0_193_bttpv",
"unit": "V"
},
{
"ID": 2,
"type": "BTTPC",
"key": "0_195_bttpc",
"unit": "A"
},
{
"ID": 3,
"type": "AVGKMKWH",
"key": "0_202_avgkmKwh",
"unit": "Km/Kwh"
}]
How can I combine these two (using the ID and type keys/values of the second json and replace the DIAGNOSTIC_TYPE_ID with those on first json)and take a result like the bellow json?
"data": [{
"DIAGNOSTIC_TYPE_ID": BTTPV,
"VALUE": "288.0"
},
{
"DIAGNOSTIC_TYPE_ID": BTTPC,
"VALUE": "-0.1"
},
{
"DIAGNOSTIC_TYPE_ID": AVGKMKWH,
"VALUE": "327.67"
},
{
"DIAGNOSTIC_TYPE_ID": BTTPV,
"VALUE": "288.0"
},
{
"DIAGNOSTIC_TYPE_ID": BTTPC,
"VALUE": "-0.1"
},
{
"DIAGNOSTIC_TYPE_ID": AVGKMKWH,
"VALUE": "327.67"
}]
Would anyone have any points or links that may know and may help?
//change to arrays
$data = json_decode(YOUR_DATA_JSON, true); // I don't know your json variable names, so replace them
$diagnosticKeys = json_decode(YOUR_DIAGNOSTIC_KEYS_JSON, true);
//iterate over data, this is the one you want to change
foreach ($data as &$dataItem) {//(& is for replacing the values)
//another foreach for diagnostic keys
foreach ($diagnosticKeys as $diagnosticKey) {
if ($dataItem["DIAGNOSTIC_TYPE_ID"] == $diagnosticKey["ID"] {
$dataItem["DIAGNOSTIC_TYPE_ID"] = $diagnosticKey["type"];
}
}
}
//change to json again
$data = json_encode($data);
Not tested but should work.
$data1 = json_decode($json1);
$data2 = json_decode($json2);
$result = [];
foreach ($data1->data as $key => $value) {
foreach($data2->diagnostics_keys as $i => $val){
if($value->DIAGNOSTIC_TYPE_ID==$val->ID){
$value->DIAGNOSTIC_TYPE_ID = $val->type;
$result[$key]['DIAGNOSTIC_TYPE_ID'] = $val->type;
$result[$key]['VALUE'] = $value->VALUE;
}
}
}
echo json_encode($result);

json data formating wrapped inside a var

I have a json data generated with the following php code
$index = array();
foreach($rows as $row)
{
$row['data'] []= (object) [];
$index[$row['cat_id']] = $row;
}
// build the tree
foreach($index as $id => &$row)
{
if ($id === 0) continue;
$parent = $row['parent'];
$index [$parent]['children'][] = &$row;
}
unset($row);
// obtain root node
$index = $index[0]['children'][0];
$json_data = json_encode($index, JSON_PRETTY_PRINT);
which produces the following json
{
"cat_id": "1",
"id": "RT",
"name": "root",
"parent": "0",
"url": "www.test.com",
"data": [
{}
],
"children": [
{
"cat_id": "4",
"id": "CI.001",
"name": "Test2",
"parent": "2",
"url": "www.test.com",
"data": [
{}
]
}
what i want is the output to be like this
var something = [{
"cat_id": "1",
"id": "RT",
"name": "root",
"parent": "0",
"url": "www.test.com",
"data": [
{}
],
"children": [
{
"cat_id": "4",
"id": "CI.001",
"name": "Test2",
"parent": "2",
"url": "www.test.com",
"data": [
{}
]
}];
I have looked through the web with some suggesting that it is not json but php array i'm new to json. How can I solve this ?
Here is is my solution at the moment.
ob_start();
echo "var javascript_array = [". $json_data . "];\n";
$content = ob_get_contents();
file_put_contents('../core/json/tree.js', $content);
Any suggestions and improvements will be appreciated.

How to get json output from php array

This is my PHP code for json output:
$sql="SELECT id,name FROM languages ORDER BY id";
$result=mysqli_query($conn,$sql);
// Fetch all
$result = mysqli_fetch_all($result,MYSQLI_ASSOC);
$out_put = json_encode($result);
echo $out_put;
This is the json output of the above php code:
{
"0": {
"id": "1",
"name": "English"
},
"1": {
"id": "2",
"name": "Kanada"
},
"2": {
"id": "3",
"name": "Hindi"
},
"3": {
"id": "4",
"name": "Telugu"
}
}
But I want output like this:
{
"Responsecode":200,
"Message":"Sucess",
"languagelist": [
{
"id": "1",
"name": "English"
},
{
"id": "2",
"name": "Kannada"
},
{
"id": "3",
"name": "Hindi"
},
{
"id": "4",
"name": "Telugu"
}
]
}
I am trying to create API and I am new in it. Please help. Thank you in advance.
Just write
$out_put = json_encode([
"Responsecode" => 200,
"Message" => "Sucess",
"languagelist" => $result
]);
You can do it by this way:
$output['Responsecode'] = 200;
$output['Message'] = "Sucess";
$output['languagelist'] = $result;
$out_put = json_encode($output);

Inserting an array values depends on data table with condition (nested array)

I have a problem , I'm just a newbie in programming and a bit low on logical problems. I want to generate an array values from a MySQL query result and it has to be nested.
My Actual Codes that i've been working on:
<?php
$mostSold_arr = array();
$subData_array = array();
$day_arr = array();
$data = array();
// Connect to MySQL
$link = new mysqli( 'localhost', 'root', '', 'db' );
if ( $link->connect_errno ) {
die( "Failed to connect to MySQL: (" . $link->connect_errno . ") " . $link->connect_error );
}
$fetch_data = mysqli_query($link, "SELECT products.id as prodID, title, SUM(total_price) as value, orders.order_date as date FROM products LEFT JOIN order_details ON order_details.product_id=products.id LEFT JOIN orders ON orders.id=order_details.order_id GROUP BY order_details.product_id ORDER BY value DESC LIMIT 2 ") or die(mysqli_error($link));
while ($row_mainData = mysqli_fetch_assoc($fetch_data)) {
$mostSold_arr['category'] = $row_mainData['title'];
$mostSold_arr['value'] = $row_mainData['value'];
$prod_id['prodID'] = $row_mainData['prodID'];
$mostSold_arr['url'] = "#";
$mostSold_arr['description'] = "click to drill-down";
$mostSold_arr['data'] = array();
$fetch_subData = mysqli_query($link, "SELECT title, SUM(total_price) as value, MONTHNAME(orders.order_date) as date FROM products LEFT JOIN order_details ON order_details.product_id=products.id LEFT JOIN orders ON orders.id=order_details.order_id WHERE order_details.product_id=" . $prod_id['prodID'] ." GROUP BY title, date ORDER BY order_date LIMIT 3 ") or die(mysqli_error($link));
while ($row_subData = mysqli_fetch_assoc($fetch_subData)) {
$subData_arr['category']=$row_subData['date'];
$subData_arr['value']=$row_subData['value'];
$day_arr['data'] = array();
array_push($mostSold_arr['data'],$subData_arr);
$fetch_subDataDay = mysqli_query($link, "SELECT title, SUM(total_price) as value, DATE_FORMAT(orders.order_date, '%M-%d') as date FROM products LEFT JOIN order_details ON order_details.product_id=products.id LEFT JOIN orders ON orders.id=order_details.order_id WHERE order_details.product_id=" . $row_mainData['prodID'] ." AND DATE_FORMAT(orders.order_date, '%M-%d') LIKE '%March%' GROUP BY date ORDER BY order_date LIMIT 3 ") or die(mysqli_error($link));
while ($row_subDataDay = mysqli_fetch_assoc($fetch_subDataDay)) {
$subDataDay_arr['category']=$row_subDataDay['date'];
$subDataDay_arr['value']=$row_subDataDay['value'];
//array_push($day_arr['data'],$subDataDay_arr);
if($subData_arr['category'] == 'March'){
array_push($mostSold_arr['data'],$subDataDay_arr);
}
//array_push($day_arr['data'],$subDataDay_arr);
//var_dump($subData_arr);
}
}
array_push($data, $mostSold_arr);
}
$jsonData = json_encode($data, JSON_PRETTY_PRINT);
$fp = fopen('dataColMultiNested.json', 'w');
fwrite($fp, $jsonData);
fclose($fp);
die('<pre>' . print_r($jsonData, 1));
mysqli_close($link);
?>
The Actual Output of the code above:
[
{
"category": "ACER E5-473-53C0",
"value": "2455200.00",
"url": "#",
"description": "click to drill-down",
"data": [
{
"category": "March",
"value": "809100.00"
},
{
"category": "March-02",
"value": "27900.00"
},
{
"category": "March-03",
"value": "27900.00"
},
{
"category": "March-04",
"value": "55800.00"
},
{
"category": "April",
"value": "781200.00"
},
{
"category": "May",
"value": "418500.00"
}
]
},
{
"category": "ACER ASPIRE E5-551G-F57K LAPTOP",
"value": "2339220.00",
"url": "#",
"description": "click to drill-down",
"data": [
{
"category": "March",
"value": "449850.00"
},
{
"category": "March-02",
"value": "29990.00"
},
{
"category": "March-03",
"value": "59980.00"
},
{
"category": "March-07",
"value": "59980.00"
},
{
"category": "April",
"value": "689770.00"
},
{
"category": "May",
"value": "779740.00"
}
]
}
Expected Output(it should be like this)
[
{
"category": "ACER E5-473-53C0",
"value": "2455200.00",
"url": "#",
"description": "click to drill-down",
"data": [
{
"category": "March",
"value": "809100.00",
"data": [
{
"category": "March-02",
"value": "27900.00"
},
{
"category": "March-03",
"value": "27900.00"
},
{
"category": "March-04",
"value": "55800.00"
}
]
},
{
"category": "April",
"value": "781200.00"
},
{
"category": "May",
"value": "418500.00"
}
]
},
{
"category": "ACER ASPIRE E5-551G-F57K LAPTOP",
"value": "2339220.00",
"url": "#",
"description": "click to drill-down",
"data": [
{
"category": "March",
"value": "449850.00",
"data": [
{
"category": "March-02",
"value": "29990.00"
},
{
"category": "March-03",
"value": "59980.00"
},
{
"category": "March-07",
"value": "59980.00"
}
]
},
{
"category": "April",
"value": "689770.00"
},
{
"category": "May",
"value": "779740.00"
}
]
}
]
I'm working on this for about 2 nights or more but can find the right solution for my problem.
I hoping that you guys can help me. Thanks.
This is a totally refunded answer, based on the information which lacked in your question and its tags: your desired result is in JSON format (but I must admit that your representation complied with it).
In PHP, you must first create an equivalent array that will look like this:
[
0 => [
"year" => "2016",
"data" => [
0 => [
"month" => "Dec",
"data" => [
0 => [
"day": "Dec 04",
],
],
],
],
],
]
It can be built with something not far from your initial code:
$fetch_data1 = "Select * From tbl1";
$year = [];
while($row_year = mysqli_fetch_assoc($fetch_data1)){
$year['year'] = $row_year['year'];
$fetch_data2 = "Select * From tbl2";
/* my query needs to loop inside because
it will contain condition depends on the retrieved data row */
$data = [];
while($row_month = mysqli_fetch_assoc($fetch_data2)){
$data['month'] = $row_month['month'];
$fetch_data3 = "Select * From tbl3";
/* my query needs to loop inside because
it will contain condition depends on the retrieved data row */
$day = [];
while($row_day = mysqli_fetch_assoc($fetch_data3)){
$day['day'] = $row_month['month'] . ' ' . $row_day['day'];
}
$data['data'] = $day;
}
$year[] = $data;
}

Fetch particular data from duplicated record in PHP

I just wanted to know is there a possibility to get specific columns from duplicated row in PHP-MySQL connection and use them to the existing data in JSON?
/...db connection etc.
if ($statement->execute())
{
$response["lecturer"] = array();
while($row = $statement->fetch(PDO::FETCH_ASSOC))
{
$lecturer = array();
$lecturer["id"] = $row["lecturerid"];
$lecturer["image"] = $row["l_image"];
$lecturer["degree"] = $row["degree"];
$lecturer["name"] = $row["l_name"];
$lecturer["surname"] = $row["surname"];
$lecturer["field"] = array();
$lecturer["field"]["fieldid"] = $row["fieldid"];
$lecturer["field"]["name"] = $row["f_name"];
array_push($response["lecturer"], $lecturer);
}
}
/... json_encode etc.
So, there can be a situation, where one lecturer has 2 different fields, and I'm getting something like this:
{
"lecturer": [
{
"id": 1,
"image": "http://...",
"degree": "PhD",
"name": "John",
"surname": "Doe",
"field": {
"fieldid": 13,
"name": "field1"
}
},
{
"id": 1,
"image": "http://...",
"degree": "PhD",
"name": "John",
"surname": "Doe",
"field": {
"fieldid": 14,
"name": "field2"
}
},
Instead of that, I would like to get JSON:
{
"lecturer": [
{
"id": 1,
"image": "http://...",
"degree": "PhD",
"name": "John",
"surname": "Doe",
"field": {
"fieldid": 13,
"name": "field1",
"fieldid": 14,
"name": "field2"
}
},
In the MySQL database there are two tables: lecturer, and field, but also lecturer_field table, where I have relation between lecturerid and fieldid.
As i was pointed out, it's impossible to declare similar named field in json object:
"field": {
"fieldid": 13,
"name": "field1",
"fieldid": 14,
"name": "field2"
}
Valid case is
"field": [{
"fieldid": 13,
"name": "field1",
},
{
"fieldid": 14,
"name": "field2"
}]
You can do that in this way:
if ($statement->execute())
{
$indexedLecturers = array();
while($row = $statement->fetch(PDO::FETCH_ASSOC))
{
$lid = $row["lecturerid"];
if (isset($indexedLecturers[$lid])) {
array_push($indexedLecturers[$lid]["field"], array(
"fieldid" => $row["fieldid"],
"name" => $row["f_name"],
));
} else {
$lecturer = array();
$lecturer["id"] = $lid;
$lecturer["image"] = $row["l_image"];
$lecturer["degree"] = $row["degree"];
$lecturer["name"] = $row["l_name"];
$lecturer["surname"] = $row["surname"];
$lecturer["field"] = array();
array_push($lecturer["field"], array(
"fieldid" => $row["fieldid"],
"name" => $row["f_name"],
));
$indexedLecturers[$lid] = $lecturer;
}
}
$response['lecturer'] = array_values($indexedLecturers);
}

Categories