Update values in 2 different .json files using PHP - 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.

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

PHP update json from received input and write back to same file

I have a json file stored on server & it looks like below:
{
"support_link":"#",
"support_link_2":"#",
"packs":[
{
"identifier":1,
"viewCount":0,
"downloadCount":0
},
{
"identifier":2,
"viewCount":0,
"downloadCount":0
}
]
}
By using PHP, I want to update the viewCount & downloadCount of some of the arrays inside packs.
But the thing is the data is received via a POST method to the server which contains another json with info. of which identifier to update & what param to update, & I am not able to update the existing file & save it back.
Received Json format:
{
"impressions": [
{
"identifier": "1",
"impressionCount": 2
},
{
"identifier": "100",
"impressionCount": 2
},
{
"identifier": "1000",
"impressionCount": 2000
}
],
"downloads": [
{
"identifier": "1",
"downloadCount": 10
}
]
}
What I've tried to do so far:
$json = file_get_contents('php://input');
if ($json != '') {
$properJsonFormatted = json_decode($json, true);
$impressions = $properJsonFormatted['impressions'];
$downloads = $properJsonFormatted['downloads'];
$testConfig =
$json = file_get_contents('php://input');
if ($json != '') {
$properJsonFormatted = json_decode($json, true);
$impressions = $properJsonFormatted['impressions'];
$downloads = $properJsonFormatted['downloads'];
$testConfig = json_decode(file_get_contents("test_config.json"),true);
$packs = $testConfig['packs'];
foreach ($packs as &$pack) {
$packIdentifier = $pack['identifier'];
foreach ($impressions as $impression) {
$impressionIdentifier = $impression['identifier'];
if ($packIdentifier == $impressionIdentifier) {
$pack['viewCount'] += $impression['impressionCount'];
$newCount = $pack['viewCount'];
print("Id: $packIdentifier, ViewCount: $newCount\n");
}
}
}
put_file_contents("test_config.json" , $testConfig);
// print_r($testConfig);
// Save back the updated test_config.json
}
}
UPDATE
Seem to have misinterpreted the question. The actual problem seems to be much simpler.
Change this:
put_file_contents("test_config.json" , $testConfig);
To this:
file_put_contents('test_config.json', json_encode($testConfig));
Also change this:
$packs = $testConfig['packs'];
To this:
$packs = &$testConfig['packs'];
As it seems you forgot to assign that by reference, while you correctly did that in the foreach.

how to access data from one website to other using api and json

I have a page where i get whole data from database
http://localhost/staff/home.php
if($btn_search =='Serach' && $btn_search !='') {
$search_field = isset($_GET['search_field'])?$_GET['search_field']:'';
$all_users = $obj->getAllUsers($search_field);
}else{
$all_users = $obj->getAllUsers();
$r = json_encode($all_users);
echo "<pre>";
print_r($r);
die();
}
here got the data in JSON format.
but now i want same data in other website and the path is
http://localhost/staff_json/
and the code i have done like this
<?php
$rs = file_get_contents('http://localhost/staff/home.php');
$obj = json_decode($rs);
echo "<pre>";
print_r($obj);
?>
the page is successfully run but data is not showing.
please help me if someone know this
In your http://localhost/staff/home.php in your else part:
else{
$all_users = $obj->getAllUsers();
$r = json_encode($all_users);
echo $r;
}
Updated my code as per your JSON:
put below JSON on "http://localhost/staff/home.php" as it is (actually this is your JSON output you are getting from your code)
[{
"id": "94",
"username": "jems",
"password": "123",
"email": "jems#gmail.com",
"mobile": "8596558499",
"address": "Banglor",
"gender": "male",
"salary": "0",
"status": "1",
"image_name": "1320294973-screenshot.jpg"
}, {
"id": "99",
"username": ".sapna",
"password": "sapna9",
"email": "sapnapapola15#gmail.com",
"mobile": "8826089668",
"address": "laxminagar",
"gender": "male",
"salary": "0",
"status": "1",
"image_name": "no-image.jpg"
}]
And below is the code your "http://localhost/staff_json/index.php"
<?php
$rs = file_get_contents("http://localhost/staff/home.php");
$obj = json_decode($rs);
echo "<pre>";
print_r($obj);
?>
I am getting the desired output
]3
AS per your code:
Prepare a separate file "userdata.php" place it to same folder where the "home.php" page /staff/userdata.php
<?php
include('config/controller.php');
$obj = new Controller();
$all_users = $obj->getAllUsers();
$r = json_encode($all_users);
echo $r;
?>
And below is the code your "http://localhost/staff_json/index.php"
<?php
$rs = file_get_contents("http://localhost/staff/userdata.php");
$obj = json_decode($rs);
echo "<pre>";
print_r($obj);
?>
Then you get the desired output:
Below is your "home.php" page PHP script:
<?php
include('config/controller.php');
$obj = new Controller();
include('header.php');
$obj->authenticate();
$all_users = '';
$search_field ='';
$btn_search = isset($_GET['btn_search'])?$_GET['btn_search']:'';
if($btn_search =='Serach' && $btn_search !='') {
$search_field = isset($_GET['search_field'])?$_GET['search_field']:'';
$all_users = $obj->getAllUsers($search_field);
}
?>
I removed your else part
Try this hope it will work for you
You need to echo you response
if($btn_search =='Serach' && $btn_search !='') {
$search_field = isset($_GET['search_field'])?$_GET['search_field']:'';
$all_users = $obj->getAllUsers($search_field);
}else{
$all_users = $obj->getAllUsers();
$r = json_encode($all_users);
echo $r;
}
Now hit the url.
AS per your comment you need the data of other project into your current project. So you need and CURL request to fetch the data from other project into your current one.
$ch = curl_init();
$curlConfig = array(
CURLOPT_URL => "http://localhost/staff/home.php",
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
);
curl_setopt_array($ch, $curlConfig);
$result = curl_exec($ch);
curl_close($ch);
$decodeData = json_decode($result);
print_r($decodeData);
Please try out the above code

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.

I want to send json response of my select query two in one

header('Content-type: application/json');
include("con.php");
$school_id=1;
$sql=mysql_query("SELECT * FROM tbl_photogallery WHERE school_id=$school_id");
$response=array();
$info=array();
while($rows=mysql_fetch_assoc($sql)){
$galleryInfo=array();
$galleryInfo["image_name"]=$rows["image_name"];
$galleryInfo["image_url"]=$rows["image_url"];
array_push($info,$galleryInfo);
}
$response["school_id"]=$school_id;
$response['info']=$info;
echo json_encode($response);
Here I am getting one for one row in my json response but I want two database row in one for photo gallery here below I mention my output and the format of response I want
My output is giving me output in this manner.
{
"sucesss": "1",
"school_id": 1,
"info": [
{
"image_name": "school1.jpg",
"image_url": "http://mydomain.in/mobi_school/photogallery/school1.jpg"
},
{
"image_name": "School2.jpg",
"image_url": "http://mydomain.in/mobi_school/photogallery/School2.jpg"
}
]
}
I want this the response of my json in this manner so that I can show my response two images in a row.
{
"sucesss": "1",
"school_id": 1,
"info": [
[
{
"image_name1": "school1.jpg",
"image_url1": "http: //geetaarts.in/mobi_school/photogallery/school1.jpg",
"image_name2": "school1.jpg",
"image_url2": "http: //geetaarts.in/mobi_school/photogallery/school1.jpg"
}
]
]
}
try something like this
header('Content-type: application/json');
include("con.php");
$school_id=1;
$sql=mysql_query("SELECT * FROM tbl_photogallery WHERE school_id=$school_id");
$response=array();
$info=array();
$info_arr=array();
while($rows=mysql_fetch_assoc($sql)){
$galleryInfo=array();
$galleryInfo["image_name"]=$rows["image_name"];
$galleryInfo["image_url"]=$rows["image_url"];
array_push($info_arr,$galleryInfo);
}
array_push($info,$info_arr);
$response["school_id"]=$school_id;
$response['info']=$info;
echo json_encode($response);
You are already getting what you need. Wrapping an array inside of another array is pointless if the outer array will only ever have one element. If you for some reason want it thought you can do it. I am going to refactor your code a bit so we can see what is going on.
$school_id=1;
$sql = mysql_query("SELECT * FROM tbl_photogallery WHERE school_id=$school_id");
$response = array("school_id" => $school_id, "info" => array());
for($i = 0; $rows=mysql_fetch_assoc($sql); $i++){
$response['info'][$i] = array();
$response['info'][$i]['image_name'] = $rows['image_name'];
$response['info'][$i]['image_url'] = $rows['image_url'];
}
your json has a random "sucesss": "1" not in your code
This is essentially the same thing you have but it is easier to understand. This is perfect because now in javascript we can access the first image like this:
var schools = JSON.parse(jsonResponseString);
var firstImage = schools['info'][0]['image_url'];
You are asking how to wrap this in an extra array though so I will show you finally. Just change my code above to:
$school_id=1;
$sql = mysql_query("SELECT * FROM tbl_photogallery WHERE school_id=$school_id");
$response = array("school_id" => $school_id, "info" => array());
for($i = 0; $rows=mysql_fetch_assoc($sql); $i++){
$response['info'][$i] = array();
$response['info'][$i][0] = array();
$response['info'][$i][0]['image_name'] = $rows['image_name'];
$response['info'][$i][0]['image_url'] = $rows['image_url'];
}
I went through all the explaining and changing up of the code to make it easier to see that it is pointless to wrap the array in an array. Hope this was helpful.
In javascript to access the first image we now have to add the extra pointless array:
var schools = JSON.parse(jsonResponseString);
var firstImage = schools['info'][0][0]['image_url'];
Note: I haven't run any of this code so I may have some syntactical errors but the ideas are all there.

Categories