How can convert query string in laravel to json - php

I have a problem here, I want to change the query string that I received to the json form as follows
{"id":"89"}
here I try to use json_encode but the one it produces is
""?id=89""
here is my code
$coba = str_replace($request->url(), '',$request->fullUrl());
if (empty($coba)) {
$url = "{}";
} else {
$url = $coba;
}
$json_body = json_encode($url);
there I also want to change if there is no query string then the result is {}

This should do it for you for both conditions:
json_encode($request->query(), JSON_FORCE_OBJECT);
PHP Manual - JSON Functions - json_encode
Laravel 5.8 Docs - Requests - Retrieving Input - Retrieving Input From The Query String query

//get Parameters
$array = [
'id' => 20,
'name' => 'john',
];
//getting the current url from Request
$baseUrl = $request->url();
//we are encoding the array because
//u said that the get parms in json format
//so that ...
$json = json_encode($array);
//now building the query based on the data
//from json by decoding it
$query = (http_build_query(json_decode($json)));
//at the end of the url you need '?' mark so...
$url = \Illuminate\Support\Str::finish($baseUrl,'?');
//now Merging it
$fullUrl = $url.$query;
dump($fullUrl);
For any issues kindly comment

Related

D3js Multi line graph convert from using CSV file

I am looking to make a multi line graph from this example.
Instead of using data from a CSV file I'm building an array of values from the database:
$token_prices = sw::shared()->prices->getForTokenID($token_id);
$token_prices_array = array();
foreach ($token_prices as $token_price) {
$token_prices_array[] = [
"date" => $token_price['date'],
"close" => $token_price['close']
];
}
$second_token_prices = sw::shared()->prices->getForTokenID(3);
$second_token_prices_array = array();
foreach ($second_token_prices as $second_token_price) {
$second_token_prices_array[] = [
"date" => $second_token_price['date'],
"close" => $second_token_price['close']
];
}
$all = array_merge($second_token_prices_array, $token_prices_array);
foreach ($all as $datapoint) {
$result[$datapoint['date']] []= $datapoint['close'];
}
Data output:
{"15-Jun-18":["8.4","0.14559"],"16-Jun-18":["8.36","0.147207"],"17-Jun-18":["8.42","0.13422"],"18-Jun-18":["8.71","0.146177"],"19-Jun-18":["8.62","0.138188"],"20-Jun-18":["8.45","0.128201"],
My issue is with plugging the data from the database in:
var tokendata = <?php echo json_encode($result) ?>;
data = tokendata;
data.forEach(function(d) {
d.date = parseTime(d.date);
d.close = +d.close;
d.open = +d.open;
});
I get an issue here "data.forEach is not a function"...
How can I fix this to use the data from the database?
Here is the Fiddle
It looks like you are embedding the results of the query php page as a JSON string -- if you want to iterate over that data as an array, you will have to parse it back into a Javascript object first.
I'm assuming that the first code snippet is running on a different server, and so the $result array is not directly available to your javascript code -- is this why you are trying to set a variable to the encoded return value? If so, it's not the best way to pull data into your page's script, but this may work for you:
var data = JSON.parse('<?php echo json_encode($result)?>');
or even:
var data = eval(<?php echo json_encode($result)?>);
Both methods assume that your result is returned as a valid json string, since there is no error checking or try/catch logic. I honestly don't know what the output of the json_encode() method looks like, so if you still can't get it working, please update your post with an example of the returned string.

Post Json array in url

Is it possible to pass JSON in a URL?
For example, I have an array:
data = {
"name": "test",
"user_id": 1
}
I want to pass it in to a URL like:
http://example.com/jsonArray
You should better use POST to pass such type of data, but, absolutely you could make a :
$str = serialize(json_decode($data, true));
And then pass you $str in url.
You can't send the JSON array directly, but you can prepare it in a way that allows it to be sent to your API. You turn your JSON into a string and encode it so it will be properly formatted for a GET.
// your JSON data
var data = '{"name":"Homer Simpson","status":"Suspended","disciplinary-dates":["2018-01-2","2018-02-14","2018-03-17"]}' ;
// take your JSON, turn it into a string and then encode it
var urlParams = encodeURIComponent(JSON.stringify(data)) ;
// your URL adding your JSON data as the value
var url = 'http://example.com/?params=' + urlParams ;
On the PHP side you will decode
// note: this code does not have any error checking - you should add it
// get your params
$params = $_GET['params'] ;
// decode the string
$decodedParams = urldecode($params) ;
// turn your string into an array
$wasJSONAsArray = json_decode($decodedParams, true) ;
// turn your string into a std object
$wasJSONAsStdObj = json_decode($decodedParams) ;

how to get post data from array input fields in getParams() in SLIM PHP

i am having a form with some array input fields like name[],age[],gender[] etc.
and i am trying to access the post data in slim php with a function using
$name = $request->getParam('name');
but iam not getting any data. Any kind of help will be appreciated. Thanks in advance.
If you want to pass an array of objects you can achieve the same by passing the value in JSON format.
For example:
My Sample JSON format is as below.
{
"news_title": "Title",
"news_description": "news_description",
"news_date": "03-12-2017",
"image_list": [
{
"imagedata": "data",
"fileName": "Imags12.png"
},
{
"imagedata": "data",
"fileName": "Imags11.png"
}
]
}
You can read this JSON data in slim as described below.
$app->post('/create_news_json', function () use ($app) {
$json = $app->request->getBody();
$data = json_decode($json, true); // parse the JSON into an assoc. array
$news_title=$data['news_title']; // to retrieve value from news_title
$news_description=$data['news_description']; // to retrieve value from news_description
$news_date = date_format(date_create($data['news_date']),"Y-m-d"); // to
retrieve value from news_date and convert the date into Y-m-d format
$news_ImageList=$data['image_list']; //read image_list array
$arr_length=count($data['image_list']);//calculate the length of the array.
// trace each elements in image_list array as follows.
for($i=0;$i<count($news_ImageList);$i++)
{
$imagedata = $news_ImageList[$i]['imagedata']; //read image_list[].imagedata element
$filename = $news_ImageList[$i]['fileName']; //read image_list[].fileName element
}
});
In postman you can pass the JSON object as row data in the format of application/json in body section.
By using this concept any kind of complex data structures can be passed into the slim as JSON object.It can accomplish most of you data passing goals.
It looks like you have the general idea, but after looking at the documentation. It seems like you need to employ slim's helpers for the post data. This is the example that the documentation displays in order to retrieve the values of title and description. As mentioned below, the filter_var() is not necessary but it is highly recommended and good practice in order to add an extra level of protection by removing any special characters that might do harm.
$app->post('/ticket/new', function (Request $request, Response $response) {
$data = $request->getParsedBody();
$ticket_data = [];
$ticket_data['title'] = filter_var($data['title'], FILTER_SANITIZE_STRING);
$ticket_data['description'] = filter_var($data['description'], FILTER_SANITIZE_STRING);
// ...
https://www.slimframework.com/docs/tutorial/first-app.html, This is the link for the example if you would like to read more about it.
$names = $request->getParam('name');
$genders = $request->getParam('gender');
$ages = $request->getParam('age');
$persons = array();
for($i=0;$i<count($names);$i++){
$arr['name'] = $names[$i];
$arr['gender'] = $genders[$i];
$arr['age'] = $ages[$i];
array_push($persons,$arr);
}
You can accesss form data sent by html form with
$name=$req->getParsedBodyParam("name");

How do i split and assign that data? [duplicate]

This question already has an answer here:
How to extract and access data from JSON with PHP?
(1 answer)
Closed 6 years ago.
How can i split that image or assign an array in PHP.
[{"ID":2,"no":123,"pname":"400","unit":"mt","bid_count":"4568","unit_price":"56","est_unit_price":"21.31","progress_count":"3841","i_project":117,"seq":0}]
I tried to split but it is a little weird.
I use this =>
$object = str_replace('[{', '', $object);
$object = str_replace('}]', '', $object);
$pieces = explode(",", $object);
// return $pieces[0];
$datas = array(
'ID' =>str_replace('"ID":','',$pieces[0]),
'poz_no'=>str_replace('"poz_no":','',$pieces[1]),
'poz_name'=>"asd",
'unit'=>str_replace('"unit":','',$pieces[3]),
'bid_count'=>str_replace('"bid_count":','',$pieces[4]),
'unit_price'=>str_replace('"unit_price":','',$pieces[5]),
'est_unit_price'=> str_replace('"est_unit_price":','',$pieces[6]),
'progress_count' =>str_replace('"progress_count":','',$pieces[7]),
'i_project'=>str_replace('"i_project":','',$pieces[8]),
'seq' =>str_replace('"seq":','',$pieces[9])
);
I did it myself but it seems weird:
$object = str_replace('[{', '', $object);
$object = str_replace('}]', '', $object);
$pieces = explode(",", $object);
$datas = array(
'ID' =>str_replace('"','',str_replace('"ID":','',$pieces[0])),
'poz_no'=>str_replace('"','',str_replace('"poz_no":','',$pieces[1])),
'poz_name'=>str_replace('"','',str_replace('"poz_name":','',$pieces[2])),
'unit'=>str_replace('"','',str_replace('"unit":','',$pieces[3])),
'bid_count'=>str_replace('"','',str_replace('"bid_count":','',$pieces[4])),
'unit_price'=>str_replace('"','',str_replace('"unit_price":','',$pieces[5])),
'est_unit_price'=>str_replace('"','',str_replace('"est_unit_price":','',$pieces[6])),
'progress_count' =>str_replace('"','',str_replace('"progress_count":','',$pieces[7])),
'i_project'=>str_replace('"','',str_replace('"i_project":','',$pieces[8])),
'seq' =>str_replace('"','',str_replace('"seq":','',$pieces[9]))
);
You can use json_decode for this.
If you have your string:
$json = '[{"ID":2,"poz_no":123,"poz_name":"400mm Muflu Beton ve C Parçası Döşenmesi","unit":"mt","bid_count":"4568","unit_price":"56","est_unit_price":"21.31","progress_count":"3841","i_project":117,"seq":0}]';
You can simply do:
$datas = json_decode($json, true);
Now in $datas you have an array with all the fields from json.
As you can see in json you have an array of objects with only one element. If you want only that first element you can do after:
$datas = $datas[0]; //get first element of array.
Your are actually dealing with a JSON encoded Data here. So, you may need to first convert the JSON Data to Standard PHP Object. And then you can simply access your preferred values using normal PHP Object Access Notation. The commented Code below attempts to illustrate (however vaguely) the Idea.
THE GIVEN JSON DATA:
<?php
$jsonString = '[{
"ID":2,
"poz_no":123,
"poz_name":"400mm Muflu Beton ve C Parçası Döşenmesi",
"unit":"mt",
"bid_count":"4568",
"unit_price":"56",
"est_unit_price":"21.31",
"progress_count":"3841",
"i_project":117,
"seq":0
}]';
THE PROCEDURE:
<?php
// CONVERT THE JSON DATA TO NATIVE PHP OBJECT...
$arrJSONData = json_decode($jsonString);
// NOW, YOU COULD ACCESS THE PHP OBJECT BY DOING: $arrJSONData[0]
$objJson = $arrJSONData[0];
// IF YOU DID IT LIKE THIS; FROM THIS POINT YOU COULD ACCESS YOUR DATA
// LIKE YOU WOULD ACCESS ANY NORMAL PHP OBJECT LIKE SO:
$id = $objJson->ID;
$pozNo = $objJson->poz_no;
$unit = $objJson->unit;
// HOWEVER, WHAT IF THE JSON DATA CONTAINS MORE THAN ONE ENTRY?
// THEN A LOOP WOULD BE NECESSARY...
// LOOP THROUGH THE RESULTING ARRAY OF OBJECTS AND GET YOUR DATA...
foreach($arrJSONData as $jsonData){
// AGAIN; YOU COULD ACCESS YOUR DATA
// LIKE YOU WOULD ACCESS ANY NORMAL PHP OBJECT LIKE SO:
$id = $objJson->ID;
$pozNo = $objJson->poz_no;
$unit = $objJson->unit;
}

Get JSON data from external form in codeigniter

I have an external web form which posts data to my controller URL. The data is sent in a JSON string.
What I need to do is get the individual values in the JSON string and add them to my database. However I'm having some trouble getting the posted values and decoding them.
Here is the code which I tried - any help would be much appreciated Thanks.
public function index() {
$this->load->view('lead');
$form_data = array(
'firstname' => json_decode($this->input->post('first_name')),
'lastname' =>json_decode($this->input->post('last_name')),
'number' =>json_decode($this->input->post('phone_number')),
'email' =>json_decode($this->input->post('email')),
'suburb' =>json_decode($this->input->post('suburb')),
'state' =>json_decode($this->input->post('state')),
'enquiry' =>json_decode($this->input->post('enquiry'))
);
// run insert model to write data to db
if ($this->AddLeadModel->SaveForm($form_data) == TRUE) // the information has therefore been successfully saved in the db { //Do something if successful }
Do not json_decode the individual form fields.
You have to json_decode the incoming field with the json instead,
then use the array data to populate the form again.
In easy words: You from fields were stuffed into an array on JS side, then json_encoded for transfer to the server. Now you need to expand the json to get the array back.
// decode the incomning json
// you get an array
$json_array = json_decode($this->input->post('the_form_field_name_of_your_json'));
// now assign the array data to the form
$form_data = array(
'firstname' => $json_array['first_name'],
...
...
);
try this:
$json = file_get_contents('php://input');
$input_data = json_decode($json, TRUE);
Will explain with an example (THIS WORKS):
// Assuming the values you are getting via POST
$first_name = '{"first_name" : "Parag"}';
$last_name = '{"last_name" : "Tyagi"}';
$phone_number = '{"phone_number" : "9999999999"}';
$form_data['firstname'] = json_decode($first_name, TRUE)['first_name'];
$form_data['lastname'] = json_decode($last_name, TRUE)['last_name'];
$form_data['number'] = json_decode($phone_number, TRUE)['phone_number'];
print_r($form_data);
DEMO:
http://3v4l.org/dmIrr
Now check below (THIS WON'T WORK):
// Assuming the values you are getting via POST
$first_name = "{'first_name' : 'Parag'}";
$last_name = "{'last_name' : 'Tyagi'}";
$phone_number = "{'phone_number' : '9999999999'}";
$form_data['firstname'] = json_decode($first_name, TRUE)['first_name'];
$form_data['lastname'] = json_decode($last_name, TRUE)['last_name'];
$form_data['number'] = json_decode($phone_number, TRUE)['phone_number'];
print_r($form_data);
DEMO:
http://3v4l.org/MeJoU
Explanation:
If you pass the JSON in your post to json_decode, it will fail. Valid JSON strings have quoted keys. Hence check your case and see in what format are you getting the JSON (via POST).

Categories