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;
?>
Related
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.
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);
(First a bit/lot of context at the bottom is the question)
I am writing an API that returns a planning amongst other things. The response is in JSON and should be as followed:
"Planning":
[
{
"Name": "Overview",
"Dates":
[
{
"Date": "yyyy-mm-dd",
"Division1": "type",
"Division2": "type"
},
{
"Date": "yyyy-mm-dd",
"Division1": "type",
"Division2": "type"
},
...
]
},
{
"Name": "Division1",
"Dates":
[
{
"Date": "yyyy-mm-dd",
"Type": "type",
"Description": "type"
},
...
]
},
...
There is the standard blok "Name": "Overview" this is always returned, and for each division the requester is a part of, a block with "Name":"Divisionname" is added to the response.
The issue I have is that the amount or names of the divisions aren't set in stone. There can be more or less depending on the deployment.
To cover for this I wrote the following code:
<?php
...
$stmt = $conn->prepare("SELECT `idDivision` FROM Division;");
$stmt->execute();
$stmt->bind_result($idDivision);
while($stmt->fetch()){
$Divisions[] = $idDivision;
$$idDivision = array();
}
...
?>
This should create an array for each division with the array name being the id of that division (correct?).
Then I get the planning data from the DB which i store in the multiple arrays that I will later use for the response building:
<?php
$stmt->bind_result($type, $date, $idDivision, $day, $description, $note);
while($stmt->fetch()){
if(checkarray($date, $arr_date) != true){
array_push($arr_date, $date);
array_push($arr_day, $day);
}
array_push($$idDivision, $type); //This should push it into the correct array.
}
?>
At the end I want to combine all this into the respons ofcourse (This is where I am lost):
<?php
for($i = 0; $i <= count($arr_date); $i++){
$planning[0]['Dates'][] = array(
"Date" => $arr_date[$i],
// How to add every division with "arrayname" => "$type" here?
);
}
?>
As in the comment above, i don't know how to add a key:value for each division that i found dynamically so that it becomes:
<?php
for($i = 0; $i <= count($arr_date); $i++){
$planning[0]['Dates'][] = array(
"Date" => $arr_date[$i],
"Division1" => $value,
"Division2" => $value,
"Division3" => $value,
// and so on for every division
);
}
?>
Is there a way to do this or should I even go about doing this a different way? I feel like I should/could use the $Divisions array.
Try out this.
for($i = 0; $i <= count($arr_date); $i++){
$planning[0]['Dates'][$i]["Date"] = $arr_date[$i];
for($j=0;$j<count($division);$j++){
$planning[0]['Dates'][$i]["division$j"] = $division[$j];
}
}
?>
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.
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.