PHP json_encode 2 arrays - php

I need to create a json with two (or more) arrays that can have other arrays inside. I did several tests, but I can never get a correct output. This is the output I would like to get to:
{
"servizi" : [
{"id": 1, "nomeservizio": "Menu","value": 1},
{"id": 2, "nomeservizio": "Prenotazione","value": 0}
],
"pietanze" : [
{"tipopietanza": "PANINI","PANINI" : [
{"id": 1, "nomepietanza": "Royal avec du fromage", "prezzo": 5.50, "ingredienti": "Hamburger di manzo, cetriolini sott'aceto, cheddar, cipolle, senape, ketchup"},
{"id": 2, "nomepietanza": "Big Belly Burger", "prezzo": 5.50, "ingredienti": "Hamburger di manzo, cipolla,senape, salsa worchester, prezzemolo, aglio, peperone, lattuga"}
]},
{"tipopietanza": "CONTORNI E STUZZICHINI", "CONTORNI E STUZZICHINI" :[
{"id":1, "nomepietanza": "Caprese", "prezzo": 4.00, "ingredienti": "Mozzarella"},
{"id":2, "nomepietanza": "Insalata", "prezzo": 3.50, "ingredienti": "Insalata"}
]}
]
}
I want to take the data from a database and this is the first part of the output where I get "servizi", now I want to get "pietanze" and put it like in the json I showed
<?php
$user = 'root';
$pass = '';
$db = 'taurosdb';
$connect = mysqli_connect("localhost", "root", "", "taurosdb");
$sql = "-query that takes me the "servizi"-";
$result = mysqli_query($connect, $sql);
$json_array = array();
while($row = mysqli_fetch_assoc($result))
{
$json_array[] = $row;
}
echo json_encode(array('servizi' => $json_array));
?>

Just make your array a variable so you can work with it. Instead of this:
echo json_encode(array('servizi' => $json_array));
You can say:
$my_big_array = ["servizi" => $json_array];
Then later on:
$my_big_array["pietanze"] = $some_other_data;
Then at the end you can output the JSON. Don't forget to set the Content-Type header.
header("Content-Type: application/json");
echo json_encode($my_big_array);

Related

How to wrap part of my JSON with brackets using PHP?

I have some JSON that looks like this:
{
"order_id":"59.1595",
"quantity":"1",
"orderline":"61b9f15a158ee",
"customer_id":"59",
"product_thumbnail":"https:\/\/website.nl\/cms\/images\/producten\/deelpaneel\/afbeeldingen\/_deelpaneel_foto_op_rvs.jpg",
"rulers":"cm",
"product_data":{
"id":"custom",
"dpi":"50",
"name":"Deelpaneel",
"size":"1000x550",
"bleed":"10",
"sides":{
"id":1,
"name":"Frontside",
"name_nl":"Voorkant",
"template_overlay":"https:\/\/website.nl\/cms\/images\/producten\/deelpaneel\/templates\/2_deelpaneel_100x55cm1cmafstandhouders.svg"
}
},
"safety":"",
"has_contour":"false",
"preview_link":"",
"redirect_link":"https:\/\/website.nl\/winkelwagen",
"procheck":"n"
}
I create it with PHP and use json_encode.
My question is how do I get brackets around the inside of sides?
Like in this example:
"sides": [
{
"id": 1,
"name": "Frontside",
"name_nl": "Voorkant",
"template_overlay": null
},
{
"id": 2,
"name": "2 side en",
"name_nl": "2 side nl",
"template_overlay": null
},
{
"id": 3,
"name": "3 side en",
"name_nl": "3 side nl",
"template_overlay": null
}
],
"safety": 10,
This is how I create that part with PHP:
<?PHP
if(!empty($uploadarray['product_data']['sides'])){
// Multiple sides
}else{
$uploadarray['product_data']['sides']['id'] = 1;
$uploadarray['product_data']['sides']['name'] = 'Frontside';
$uploadarray['product_data']['sides']['name_nl'] = 'Voorkant';
$uploadarray['product_data']['sides']['template_overlay'] = $templateoverlay;
}
?>
Then I create the entire JSON with: $json = json_encode($uploadarray);
I've read that you need to wrap it in another array but I can't get it to work.
For example:
array(array($uploadarray['product_data']['sides']['id'] = 1));
Or
array($uploadarray['product_data']['sides']['name'] = 'Frontside');
Just output the same json result.
First create your array
$side = [
'id' => 1,
'name' => 'Frontside',
'name_nl' => 'Voorkant',
'template_overlay' => $templateoverlay
];
Then, add it :
// Check this -----------------------vv
$uploadarray['product_data']['sides'][] = $side;
Your $sides variable does not contain an array with multiple entities but just one "dictionary" (one JSON object). If you e.g. add a loop around, it should work:
<?php
// loop over whatever generates the sides
$sides_array = [];
$sides_array['id'] = 1;
$sides_array['name'] = 'Frontside';
$sides_array['name_nl'] = 'Voorkant';
$sides_array['template_overlay'] = $templateoverlay;
if(empty($uploadarray['product_data']['sides'])){
// initialize "sides"
$uploadarray['product_data']['sides'] = [];
}
$uploadarray['product_data']['sides'][] = $sides_array;
?>

Is there a way to create an array of objects using php and create an json file from it

I'm trying to create an array of objects with data coming from multiple tables, lets say there is table that hold patient data and there is table that hold diagnosis, and medicine for every patient that admitted to clinic, and i need to create an array of objects with the following output.
Screen shot
And i have to write the following code
<?php
// Db configs.
define('HOST', 'localhost');
define('PORT', 3306);
define('DATABASE', 'new_nhif');
define('USERNAME', 'root');
define('PASSWORD', '');
error_reporting(E_ALL);
ini_set('display_errors', 1);
$mysqliDriver = new mysqli_driver();
$mysqliDriver->report_mode = (MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$connection = new mysqli(HOST, USERNAME, PASSWORD, DATABASE, PORT);
$sql = sprintf(
'SELECT
nh.MembershipNo,
nh.FullName,
nh.id as nhid,
lb.labrequest,
fd.diagnosis,
fd.DiseaseCode,
fd.CreatedBy as fdcrb,
dz.name
FROM nhif_data AS nh
LEFT JOIN laboratory AS lb ON lb.re_id = nh.id
LEFT JOIN foliodisease AS fd ON fd.re_id = nh.id
LEFT JOIN dawa_zilizotoka AS dz ON dz.re_id = nh.id
WHERE lb.re_id = nh.id
AND fd.re_id = nh.id
AND dz.re_id = nh.id
-- GROUP BY nh.MembershipNo
'
);
$obj = new stdClass;
$result = $connection->query($sql);
$vipimo = array();
$dawa = array();
$all = array();
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
// print_r(json_encode(['entities'=> $row],JSON_PRETTY_PRINT));
$obj->MembershipNo = $row['MembershipNo'];
$obj->FullName = $row['FullName'];
$id = $row['nhid'];
$sql2 = "SELECT * FROM foliodisease WHERE re_id ='$id'";
$result1 = $connection->query($sql2);
if ($result1->num_rows > 0) {
while($row2 = $result1->fetch_assoc()) {
$vipimo['diagnosis']= $row2['diagnosis'];
$vipimo['DiseaseCode']= $row2['DiseaseCode'];
$obj->FolioDiseases[] = $vipimo;
}
}
$sql3 = "SELECT * FROM dawa_zilizotoka WHERE re_id = $id";
$result3 = $connection->query($sql3);
if ($result3->num_rows > 0) {
while($row3 = $result3->fetch_assoc()) {
$dawa['name']= $row3['name'];
$obj->FolioItems[] = $dawa;
}
}
$all[] = $obj;
}
print_r(json_encode(['entities'=> $all], JSON_PRETTY_PRINT));
}
?>
And it give out the following output
{
"entities": [
{
"MembershipNo": "602124502",
"FullName": "Omari M Simba",
"FolioDiseases": [
{
"diagnosis": "typhoid",
"DiseaseCode": "J54"
},
{
"diagnosis": "homa",
"DiseaseCode": "L54"
},
{
"diagnosis": "malaria",
"DiseaseCode": "b54"
}
],
"FolioItems": [
{
"name": " Fluticasone furoate\t"
},
{
"name": " Acyclovir Eye ointment\t"
},
{
"name": " Acyclovir\t"
},
{
"name": " Acyclovir\t"
}
]
},
{
"MembershipNo": "602124502",
"FullName": "Omari M Simba",
"FolioDiseases": [
{
"diagnosis": "typhoid",
"DiseaseCode": "J54"
},
{
"diagnosis": "homa",
"DiseaseCode": "L54"
},
{
"diagnosis": "malaria",
"DiseaseCode": "b54"
}
],
"FolioItems": [
{
"name": " Fluticasone furoate\t"
},
{
"name": " Acyclovir Eye ointment\t"
},
{
"name": " Acyclovir\t"
},
{
"name": " Acyclovir\t"
}
]
}
]
}
My tables are
nhif_data ----
nhif_data ,
laboratory ----
laboratory,
foliodisease ---
foliodisease ,
dawa_zilizotoka ----
dawa_zilizotoka
You don't need to create an object array for the desired output, 'json_encode()' basically objectifies anything, meaning, no matter what you store with 'json_encode()' function, 'json_decode()' will always return you an object/array of objects, and so on.
All you need to fetch the records off the database, make child nesting as required, append the record to an array, and just 'json_encode()'; with 'json_decode()', you will end up with an array of objects.
$JSONItem = []; // Initialize the array
while($Record = $Query->fetch_assoc()){ // Iterate through main recordset
...subsequent child query
// Iterate though child recordset
while($ChildRecord = $ChildQuery->fetch_assoc())$Record["Child"][] = $ChildRecord; // Append child node to main record
$JSONItem[] = $Record; // Append record for JSON conversion
}
var_dump(json_decode(json_encode($JSONItem))); // This should return an array of ojects
Following should allow a better understanding of the mechanism;
var_dump(json_decode(json_encode([
["ID" => 1, "Name" => "Apple", "Source" => ["Name" => "Amazon", "URL" => "http://Amazon.Com", ], ],
["ID" => 2, "Name" => "Banana", "Source" => ["Name" => "eBay", "URL" => "http://eBay.Com", ], ],
["ID" => 3, "Name" => "Carrot", "Source" => ["Name" => "GearBest", "URL" => "http://GearBest.Com", ], ],
])));
Or, with newer PHP version, I hope you can simply prepare/construct the array and objectify it with something like;
$JSON = (object) $JSONItem;

Update values in 2 different .json files using PHP

I have 2 .json files, one containing questions and answers with categories and one containing the categories. Here are small parts of the .json files:
category.json
[{
"category": "Algemeen"
}]
questions.json
[{
"category": "Algemeen",
"question": "123",
"answer": "123",
"date": "03-12-18 08:48:16"
}]
I have created an overview for the categories, where I can add, edit and delete a category. I have also created an overview for the questions and answers.
When editing the category in the category overview, it will post this into the .json file using the following code:
<?php
//get the index from URL
$index = $_GET['index'];
//get json data
$data = file_get_contents('category.json');
$data_array = json_decode($data);
//assign the data to selected index
$row = $data_array[$index];
?>
<?php
if(isset($_POST['save'])){
//set the updated values
$input = array(
'category' => $_POST['category'],
);
//update the selected index
$data_array[$index] = $input;
//encode back to json
$data = json_encode($data_array, JSON_PRETTY_PRINT);
file_put_contents('category.json', $data);
header('location: category.php');
}
?>
When "Algemeen" is edited into "Algemeen1" using my simple form with save button, this will edit category.json using the code above. This will change into:
[{
"category": "Algemeen1"
}]
However, the goal is to have the categories "synced", so that when you edit any category that also exists in questions.json, it also edits the value of category in questions.json. This has to result into:
[{
"category": "Algemeen1",
"question": "123",
"answer": "123",
"date": "03-12-18 08:48:16"
}]
How can I do this?
I would do something like this:
<?php
//get the index from URL
$index = $_GET['index'];
//get json data
$category_data = file_get_contents('category.json');
$category_data_array = json_decode($data);
$questions_data = file_get_contents('questions.json');
$questions_data_array = json_decode($data);
// get the old category name
$row = $category_data_array[$index];
$old_category = $row->category;
?>
<?php
if(isset($_POST['save'])){
//set the updated values
$input = array(
'category' => $_POST['category'],
);
//update the selected index
$category_data_array[$index] = $input;
// find old category, make new
foreach($questions_data_array as $question){
if ($question->category == $old_category) {
$question->category = $_POST['category'];
break;
}
}
//encode back to json
$category_data = json_encode($category_data_array, JSON_PRETTY_PRINT);
file_put_contents('category.json', $category_data);
$questions_data = json_encode($questions_data_array, JSON_PRETTY_PRINT);
file_put_contents('questions.json', $questions_data);
header('location: category.php');
}
?>
Caveat: I did not test this code. It's like pseudo-code in the shape of actual code.

JSON to MySql using PHP

Hi and I need your help
I'm working on a project for class, I'm looking to write from JSON to a MySql database.
The JSON looks like this
{
"offset": 0,
"results": [
{
"aq1": 22,
"aq3": 27,
"aq2": 27,
"ateam/_source": "/nba/teams/page/NO/new-orleans-pelicans",
"aq4": 24,
"hqf/_source": "108",
"hq2": 27,
"hq1": 22,
"hq4": 36,
"hq3": 23,
"aqf/_source": "100",
"ateam/_text": "New Orleans",
"aq3/_source": "27",
"hq4/_source": "36",
"hteam": "http://www.cbssports.com/nba/teams/page/BOS/boston-celtics",
"aq2/_source": "27",
"hteam/_text": "Boston",
"aq1/_source": "22",
"hteam/_source": "/nba/teams/page/BOS/boston-celtics",
"ateam": "http://www.cbssports.com/nba/teams/page/NO/new-orleans-pelicans",
"aqf": 100,
"hq1/_source": "22",
"hq3/_source": "23",
"hq2/_source": "27",
"hqf": 108,
"aq4/_source": "24"
},
],
"cookies": [],
"connectorVersionGuid": "dgsadjgofsjkgkfsmghjfhf",
"connectorGuid": "fbcjsdbgfjdjgkf",
"pageUrl": "http://xsftbfbjjjsfaf.com/"
}
and my php reads like this
<?php
$server = "localhost";
$username = "lies";
$password = "madeup";
$database = "dgjsfdgjv";
mysql_connect($server,$username,$password) or die("Failed");
mysql_select_db($database) or die("Database Failed");
$url = "https://api.import.io/store/data/jjjjj-ec0f-4553-bda5-def61ca1756c/_query?input/webpage/url=http%3A%2F%2Fwww.jjjjj.com%2Fnba%2Fscoreboard%2F20150111&_user=f1508a78-05c5-4487-9219-51a990391329&_apikey=aLZu2wmRCvUlBwopi%2F6Kj%2F4wnscvZRh7DYQf80LE2e3hL22rtAp0nJ3lujy10cyx9JC9Ed73xb3zGp3aArhYDQ%3D%3D";
$string = file_get_contents($url);
$arr = json_decode($string, true);
foreach($arr as $item){
$aq1 = $item['aq1'];
$aq3 = $item['aq3'];
$aq2 = $item['aq2'];
$ateam/_source = $item['aqeam/_source'];
$aq4 =$item['aq4'];
$hqf/_source =$item['aqf/_source'];
$hq2 =$item['aq2'];
$hq1 =$item['aq1'];
$hq4 =$item['aq4'];
$hq3 =$item['aq3'];
$aqf/_source =$item['aqf/_source'];
$ateam/_text =$item['aqeam/_text'];
$aq3/_source =$item['aq3/_source'];
$hq4/_source =$item['aq4/_source'];
$hteam =$item['aqeam'];
$aq2/_source =$item['aq2/_source'];
$hteam/_text =$item['aqeam/_text'];
$aq1/_source =$item['aq1/_source'];
$hteam/_source =$item['aqeam/_source'];
$ateam =$item['aqeam'];
$aqf =$item['aqf'];
$hq1/_source =$item['aq1/_source'];
$hq3/_source =$item['aq3/_source'];
$hq2/_source =$item['aq2/_source'];
$hqf =$item['aqf'];
$aq4/_source =$item['aq4/_source'];
mysql_query("INSERT INTO createdb (aq1,aq3,aq2,ateam/_source,aq4,hqf/_source,hq2,hq1,hq4,hq3,aqf/_source,ateam/_text,aq3/_source,hq4/_source,hteam,aq2/_source, hteam/_text,aq1/_source,hteam/_source,ateam,aqf,hq1/_source,hq3/_source,hq2/_source,hqf,aq4/_source) VALUES('$aq1','$aq3','$aq2','$ateam/_source','$aq4','$hqf/_source','$hq2','$hq1','$hq4','$hq3','$aqf/_source','$ateam/_text', '$aq3/_source','$hq4/_source','$hteam','$aq2/_source','$hteam/_text','$aq1/_source','$hteam/_source','$ateam','$aqf','$hq1/_source','$hq3/_source','$hq2/_source','$hqf','$aq4/_source')") or die ("Failed");
}
I dont trigger any of the error messages to appear but no data ends up in the database. What am I doing wrong? Is it the php code reading the json string correctly???
By carefully, looking at your problem , I have realized that , the problem was inside foreach() Loop. It should be
foreach($arr as $item){
echo $aq1 = $item[0]['aq1']; # note that [0] here
echo $aq3 = $item[0]['aq3'];
#...........Rest of Loop
}
And also rename variables like this $aqf/_source to $aqf_source , and so on .
I got it working.
foreach ($phpArray['results'] as $key => $value) {
// This is to make the data to be saved into the database
foreach ($value as $k => $v) {
$aq1 = $value['aq1'];
$aq3 = $value['aq3'];
$aq2 = $value['aq2'];
$ateam_source = $value['ateam/_source'];
$aq4 =$value['aq4'];
$hqf_source =$value['hqf/_source'];
$hq2 =$value['aq2'];
$hq1 =$value['aq1'];
$hq4 =$value['aq4'];
$hq3 =$value['aq3'];
$aqf_source =$value['aqf/_source'];
$ateam_text =$value['ateam/_text'];
$aq3_source =$value['aq3/_source'];
$hq4_source =$value['hq4/_source'];
$hteam =$value['hteam'];
$aq2_source =$value['aq2/_source'];
$hteam_text =$value['hteam/_text'];
$aq1_source =$value['aq1/_source'];
$hteam_source =$value['hteam/_source'];
$ateam =$value['ateam'];
$aqf =$value['aqf'];
$hq1_source =$value['hq1/_source'];
$hq3_source =$value['hq3/_source'];
$hq2_source =$value['hq2/_source'];
$hqf =$value['hqf'];
$aq4_source =$value['hq4/_source'];
}

Why I can't return a proper json structure?

I'm facing an issue regarding the json structure.
I have this:
function loadActiveTrackers($host_l, $username_l, $password_l, $dbName_l, $companyId_l){
$trackerId = 0;
$trackerName = "";
$trackerCreator = "";
$projectName = "";
$dataArray = [];
$trackerIdsArray = [];
$trackerNamesArray = [];
$trackerCreatorsArray = [];
$projectNamesArray = [];
$mysqli = new mysqli($host_l, $username_l, $password_l, $dbName_l);
$getActiveTrackersQuery = "SELECT tracker_id, tracker_name, tracker_creator, project_name FROM trackers WHERE "
. "company_id = ? AND is_active=1 ORDER BY tracker_creation_date";
if($stmt = $mysqli->prepare($getActiveTrackersQuery)){
$stmt->bind_param('s',$companyId_l);
$stmt->execute();
/* Store the result (to get properties) */
$stmt->store_result();
/* Bind the result to variables */
$stmt->bind_result($trackerId, $trackerName, $trackerCreator, $projectName);
while ($stmt->fetch()) {
$trackerIdsArray[] = $trackerId;
$trackerNamesArray[] = $trackerName;
$trackerCreatorsArray[] = $trackerCreator;
$projectNamesArray[] = $projectName;
}
$dataArray['ids'] = $trackerIdsArray;
$dataArray['names'] = $trackerNamesArray;
$dataArray['creators'] = $trackerCreatorsArray;
$dataArray['projectNames'] = $projectNamesArray;
// print_r($trackerIdsArray);
/* free results */
$stmt->free_result();
/* close statement */
$stmt->close();
}
/* close connection */
$mysqli->close();
echo json_encode($dataArray);
}
The above code works ok, but the structure is not valid.
What I mean is that it returns:
{
"ids": [1,2,3,4],
"names": ["1","2","test tracker","test1"],
"creators": ["1","test","test","test"],
"projectNames": ["1","1","test project","test"]
}
But it is supposed to return:
[
{"id": 1, "name": "1", "creator": "1", "projectName": "1"},
{"id": 2, "name": "2", "creator": "test", "projectName": "1"},
{"id": 3, "name": "test tracker", "creator": "test", "projectName": "test project"},
{"id": 4, "name": "test1", "creator": "test", "projectName": "test"}
]
Can you guide me trough it? I know that it's something really small, but I'm not able to spot it as a php newbie. In java the json library is pretty strong and with a single push() it can be achieved, but here I really can't find the way.
The current code creates arrays of the ids, names, creators, and project names.
So, instead of this code:
while ($stmt->fetch()) {
$trackerIdsArray[] = $trackerId;
$trackerNamesArray[] = $trackerName;
$trackerCreatorsArray[] = $trackerCreator;
$projectNamesArray[] = $projectName;
}
$dataArray['ids'] = $trackerIdsArray;
$dataArray['names'] = $trackerNamesArray;
$dataArray['creators'] = $trackerCreatorsArray;
$dataArray['projectNames'] = $projectNamesArray;
Change your structure to be like so:
while ($stmt->fetch()) {
$dataArray[] = array( 'id' => $trackerId,
'name' => $trackerName,
'creator' => $trackerCreator,
'projectName' => $projectName
);
}
echo json_encode($dataArray);
This will return the structure you desire, which is arrays of the ids, names, creators, and project names.

Categories