JSON PHP server modified - php

The following is my JSON data.
[
{
"id": 1,
"Name": {
"FirstName": "Wilmer",
"LastName": "Crona",
"FullName": "Mr. Cameron Prosacco"
},
"Address": {
"Address1": "84154 Vickie Burg Apt. 994",
"Address2": "Suite 339",
"ZipCode": "89080-0376"
},
"Phone": "316-269-7694 x1364"
},
{
"id": 2,
"Name": {
"FirstName": "Mercedes",
"LastName": "Kshlerin",
"FullName": "Dr. Kellie Bashirian"
},
"Address": {
"Address1": "12638 Cali Spurs",
"Address2": "Suite 353",
"ZipCode": "76622"
},
"Phone": "319-329-3169 x8848"
}
]
Here is where I want my JSON like this: https://github.com/Zlob/php-json-server but in the method. The JSON file must one file and process only one JSON (db.json).
If my JSON file json1.json , json2.json, etc. How should I do?

You can't decode only first element, you can decode all and get first element only, here is online compiler
<?php
$json = '[
{
"id": 1,
"Name": {
"FirstName": "Wilmer",
"LastName": "Crona",
"FullName": "Mr. Cameron Prosacco"
},
"Address": {
"Address1": "84154 Vickie Burg Apt. 994",
"Address2": "Suite 339",
"ZipCode": "89080-0376"
},
"Phone": "316-269-7694 x1364"
},
{
"id": 2,
"Name": {
"FirstName": "Mercedes",
"LastName": "Kshlerin",
"FullName": "Dr. Kellie Bashirian"
},
"Address": {
"Address1": "12638 Cali Spurs",
"Address2": "Suite 353",
"ZipCode": "76622"
},
"Phone": "319-329-3169 x8848"
}
]';
$data = json_decode($json);
$firstObject = $data[0];
var_dump($firstObject);

pass database name in url and set the db name in config. put all your json file inside db folder.
namespace App\Http\Controllers;
use Request;
use Response;
use Config;
use JsonServer\JsonServer;
class JsonServerController extends Controller
{
public function handleRequest($db, $uri)
{
$data = Request::all();
$method = Request::method();
$pathToJson = storage_path($db .'.json'); //if your path in inside storage folder of laravel
Config::set('pathToDb', $pathToJson); //here we set db
$jsonServer = new JsonServer();
$response = $jsonServer->handleRequest($method, $uri, $data);
$response->send();
}
}
Now define in routes
Route::any('api/{db}/{all}', "JsonServerController#handleRequest")->where('all', '.*');
Now the request will be like this for json1 database
GET api/json1/posts
POST api/json1/posts
PUT api/json1/posts/1
PATCH api/json1/posts/1
DELETE api/json1/posts/1
For json2 database
GET api/json2/posts
POST api/json2/posts
PUT api/json2/posts/1
PATCH api/json2/posts/1
DELETE api/json2/posts/1

Related

How do i make a variable value changeable in different blocks of code in php,laravel

The task is to fetch json user data from an api and store it in array. Then be able to make changes to it different routes.
Here is a sample of the data from the api, they are 10 in total and in an array.
{
"id": 1,
"name": "Leanne Graham",
"username": "Bret",
"email": "Sincere#april.biz",
"address": {
"street": "Kulas Light",
"suite": "Apt. 556",
"city": "Gwenborough",
"zipcode": "92998-3874",
"geo": {
"lat": "-37.3159",
"lng": "81.1496"
}
},
"phone": "1-770-736-8031 x56442",
"website": "hildegard.org",
"company": {
"name": "Romaguera-Crona",
"catchPhrase": "Multi-layered client-server neural-net",
"bs": "harness real-time e-markets"
}
},
{
"id": 2,
"name": "Ervin Howell",
"username": "Antonette",
"email": "Shanna#melissa.tv",
"address": {
"street": "Victor Plains",
"suite": "Suite 879",
"city": "Wisokyburgh",
"zipcode": "90566-7771",
"geo": {
"lat": "-43.9509",
"lng": "-34.4618"
}
},
"phone": "010-692-6593 x09125",
"website": "anastasia.net",
"company": {
"name": "Deckow-Crist",
"catchPhrase": "Proactive didactic contingency",
"bs": "synergize scalable supply-chains"
}
},
i fetched the data using this:
$jsonurl = "http://jsonplaceholder.typicode.com/users";
$json = file_get_contents($jsonurl);
global $userData;
$userData = json_decode($json);
I displayed the data in a /users route with this
Route::get('/users', function(){
global $userData;
echo json_encode($userData);
});
I was told to get set a /delete route that deletes the last object from the array.
Route::get('/delete', function(){
global $userData;
$lastObjIndex = count($userData) -1;
array_splice($userData, $lastObjIndex,1);
//print_r('last user deleted');
echo json_encode($userData);
$userData = $userData;
});
The problem is that the delete route does not only works once(it does not delete subsequent last objects and returns the same thing when the route is accessed again) and does not show any change in when i access the users route. The data isn't stored in the server.
I feel there is something i don't know about that could help with this. Any suggestion would be appreciated.

Get values from json using angularjs

I am making a login app in ionic using PHP, I have a login function which works well but I need to be able to store certain values to local storage for later use.
Here is a sample from my code:
$scope.login = function() {
Login.login($scope.login).then(function (data) {
if (Object.keys(data.data).length === 1) {
var datao = angular.toJson(data);
$scope.profile = datao;
$scope.email = $scope.profile.email;
$scope.username = $scope.profile.username;
console.log(data);
console.log($scope.profile);
// $state.go('dashboard');
}
....
});
....
});
$scope.profile displays the following:
[Log]
{
"data": [{
"id": "5",
"username": "ozombo",
"reputation": "ceo",
"activate": "8425",
"followercount": "3",
"praycount": "0",
"donetour": "0",
"fb_id": "0",
"fullname": "Adebambo Oyelaja",
"church": "RCCG ",
"photo": "1417451697.jpg",
"twtr_id": "0",
"screen_name": "",
"email": "oyexs911#yahoo.com",
"bio": "Geek, Father, Husband",
"country": "Nigeria",
"state": "Lagos",
"followscount": "0",
"account": "",
"password": "5cf1bc1b9a2ada1ae9e29079aae1aefa",
"signup_date": "1413305984",
"signupdevice": "web",
"keycode": "5fc868f0767b0c164341a9e8e35edbe4",
"last_login": "1436519269",
"city": "Palmgroove",
"campaign": "",
"bday": "29-09-1988",
"gender": "Male",
"approved": "0",
"donewelcome": "0",
"phonenumber": "07017993683",
"secure": "private",
"churchid": "1",
"views": "68",
"marital": "Married"
}],
"status": 200,
"config": {
"method": "GET",
"transformRequest": [null],
"transformResponse": [null],
"url": "http://localhost:8888/opb/api/login.php?user=oyexs911#yahoo.com&pass=oyelaja",
"headers": {
"Accept": "application/json, text/plain, /"
}
},
"statusText": "OK"
}
How will I get the user email for example
You can get the email by accesing to data.email like var email = $scope.profile.data.email
You forgot that you have data before you can get the email.
{
"data": [{
"username": "ozombo",
"email": "oyexs911#yahoo.com",
...
}]
}
You can get access to the user email by iterating over the data array:
$scope.profile.data.forEach(function(d) {
console.log(d.email);
});
Hope that helps!

mongodb insert field in single array document

I have a document in mongodb that looks like this
{
"_id": ObjectId("5378da275ad972a811c119fb"),
"name": "test test",
"fname": "test",
"lname": "test",
"phone": "13254355554",
"user": "525518965ad972636d7aa0ae",
}
And i want to insert a new field for "employee_id" so the result should be exactly like this.
{
"_id": ObjectId("5378da275ad972a811c119fb"),
"name": "test test",
"fname": "test",
"lname": "test",
"employee_id": "09872",
"phone": "13254355554",
"user": "525518965ad972636d7aa0ae",
}
I have used $push and $addToSet but the results became an array like
"employee_id": {
"0": "09872",
}
Just use $set;
db.test.update(
{ _id:ObjectId("5378da275ad972a811c119fb") }, // Update this id only
{ $set:{"employee_id": "09872"} } // by setting employee_id
)
Use the $set operator, $push and $addToSet are for arrays:
db.collection.update({}, {'$set': { "employee_id": "09872" } })

Decode json in php and create variables

I a trying to decode a json callback.
The json code is posted to callback.php - Here is an example of the json:
{
"order": {
"id": "5RTQNACF",
"created_at": "2012-12-09T21:23:41-08:00",
"status": "completed",
"total_btc": {
"cents": 100000000,
"currency_iso": "BTC"
},
"total_native": {
"cents": 1253,
"currency_iso": "USD"
},
"custom": "order1234",
"receive_address": "1NhwPYPgoPwr5hynRAsto5ZgEcw1LzM3My",
"button": {
"type": "buy_now",
"name": "Alpaca Socks",
"description": "The ultimate in lightweight footwear",
"id": "5d37a3b61914d6d0ad15b5135d80c19f"
},
"transaction": {
"id": "514f18b7a5ea3d630a00000f",
"hash": "4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b",
"confirmations": 0
},
"customer": {
"email": "coinbase#example.com",
"shipping_address": [
"John Smith",
"123 Main St.",
"Springfield, OR 97477",
"United States"
]
}
}
}
I can echo the json and get the following response:
{"order""id":null,"created_at":null,"status":"completed","total_btc":{"cents":100000000,"currency_iso":"BTC"},"total_native":{"cents":83433,"currency_iso":"USD"},"custom":"123456789","receive_address":"1A2qsxGHo9KjtWBTnAopTwUiBQf2w6yRNr","button":{"type":"buy_now","name":"Test Item","description":null,"id":null},"transaction":{"id":"52d064b59eeb59985e00002c","hash":"4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b","confirmations":0}}}
However if I try to decode the json using the following:
$array = json_decode($jsonString, true);
echo $array;
I get the following response: "200 Array"
I want to be able turn each json parameter in to a php variable.
You can access the variables within $array, for example by doing:
echo $array['custom']; // prints out "order1234"
You don't want to extract the variables directly into the local lexical scope of your program as that would create security concerns. Just use the data as indicated in the snippet above.

Parse Nested JSON With JQuery

I'm new to JSON and really struggling with this. I've read countless other posts and web pages but can't seem to figure it out.
I'm using PHP to output JSON (from data from the database) with this code:
header('Content-type: application/json');
echo json_encode($data);
Here is the JSON:
{
"x0": {
"id": "1",
"name": "Rob",
"online": "1",
"gender": "m",
"age": "29",
"height": "5'8''",
"build": "Average",
"ethnicity": "White",
"description": "Art geek person",
"looking_for": "Anything",
"image": "4fs5d43f5s4d3f544sdf.jpg",
"last_active": "29-06-11-1810",
"town": "Manchester",
"country": "UK",
"distance": 0.050973560712308
},
"x1": {
"id": "2",
"name": "Dave",
"online": "1",
"gender": "m",
"age": "29",
"height": "5'8''",
"build": "Average",
"ethnicity": "White",
"description": "Art geek person",
"looking_for": "Anything",
"image": "4fs5d43f5s4d3f544sdf.jpg",
"last_active": "29-06-11-1810",
"town": "Manchester",
"country": "UK",
"distance": 0.050973560712308
}
}
I think the problem I'm having is that the JSON is nested(might be wrong there)?.
This is the JQuery:
function fetchProfiles() {
var url='http://url.com/here';
var i = 0;
var handle = 'x'.i;
$.getJSON(url,function(json){
$.each(json.results,function(i,profile){
$("#profiles").append('<p><img src="'+profile.handle.image+'" widt="48" height="48" />'+profile.handle.name+'</p>');
i++;
});
});
}
Any ideas or suggestions appreciated!
Thanks!
i think that the problem is that you call $.each on json.results (if the json is exactly what you showed us).
you sholud do:
$.each(json,function(i,profile){
$("#profiles").append('<p><img src="'+profile.image+'" widt="48" height="48" />'+profile.name+'</p>');
});
look at the fiddle here: http://jsfiddle.net/ENcVd/1/ (it alerst the image property of you json object)

Categories