Remove item from JSON returned from API - php

I'm new to PHP and have some trouble trying to delete an item from some data returned by an API
function getData()
{
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
curl_setopt($ch, CURLOPT_POSTFIELDS, "");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json',));
$data = curl_exec($ch);
echo $data;
exit();
}
Here is the JSON data, I want to remove the item with Id 11, how can I do this?
{
"Data": [
{
"Id": 11,
"Name": "Name1"
},
{
"Id": 12,
"Name": "Name2"
}
]
}

Decode the data.
Remove the item from the array.
Optionally encode it again as string if needed.
$dataArray = json_decode($data, true);
foreach ($dataArray['Data'] as $key => $item) {
if ($item['Id'] === 11) {
unset($dataArray['Data'][$key]);
}
}
$data = json_encode($dataArray);

it will work
$dataArray = json_decode($data, true);
$dataArray['Data'] = array_filter($dataArray['Data'], function($el){return $el["Id"]<>11;});
$data = json_encode($dataArray);

One way is to re-index by Id and unset it:
$array = array_column(json_decode($data, true)['Data'], null, 'Id'));
unset($array[11]);
Now $array is indexed by Id. If you want to reset it, then:
$array = array_values($array);

Related

using variables GraphQL PHP

I'm using the FXHash API to access listings with this query:
query Listings($sort: ListingsSortInput) {
listings(sort: $sort) {
amount
createdAt
price
issuer {
name
}
objkt {
name
}
}
}
$options = '{
"sort": {
"createdAt": "DESC"
}
}';
I'd like to use the query above in PHP with the sort by createdAt options. How can I fit this query in to my cURL with the sort options? I don't understand how to add the $options variable into the query. Thanks for the help!
$url = 'https://api.fxhash.xyz/graphql';
$curl = curl_init();
$queryData = array();
$data = array();
$queryData = '{
listings {
amount
createdat
price
issuer {
name
}
objkt {
name
}
}
}';
$data["query"] = $queryData;
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_POST, TRUE);
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($curl, CURLOPT_HEADER, FALSE);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json'
));
You must add the POST request variables as a JSON map.
Try something like this:
$queryData = 'query Listings($sort: ListingsSortInput) {
listings(sort: $sort) {
amount
createdAt
price
issuer {
name
}
objkt {
name
}
}
}';
$options = '{
"sort": {
"createdAt": "DESC"
}
}';
$data["query"] = $queryData;
$data["variables"] = $options;

JSON write out with PHP [duplicate]

This question already has an answer here:
How to extract and access data from JSON with PHP?
(1 answer)
Closed 3 years ago.
I have a JSON message, and I dont know How can I write out a part of json.
I tried:
{{$data[0]->items[0]}}
{{$data[0]->name}}
{{$data->items[0]-name}}
{{$data[0]->items}}
ect...
JSON message:
{
"items":[
{
"name":"Knight",
"id":26000000,
"maxLevel":13,
"iconUrls":{
"medium":"https:\/\/api-assets.clashroyale.com\/cards\/300\/jAj1Q5rclXxU9kVImGqSJxa4wEMfEhvwNQ_4jiGUuqg.png"
}
},
{
"name":"Archers",
"id":26000001,
"maxLevel":13,
"iconUrls":{
"medium":"https:\/\/api-assets.clashroyale.com\/cards\/300\/W4Hmp8MTSdXANN8KdblbtHwtsbt0o749BbxNqmJYfA8.png"
}
}
]
}
EDIT:
This is the Controller
As you see $data array is decoded
It looks like your post is mostly code; please add some more details. omg
$token = "token";
$url = "https://api.clashroyale.com/v1/cards";
$ch = curl_init($url);
$headr = array();
$headr[] = "Accept: application/json";
$headr[] = "Authorization: Bearer ".$token;
curl_setopt($ch, CURLOPT_HTTPHEADER, $headr);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$res = curl_exec($ch);
$data = json_decode($res, true);
curl_close($ch);
return view('clash', ['data' => $data]);
First you have to decode your JSON-String to a PHP-Array and then you can access it easily this way:
$json = '{
"items":[
{
"name":"Knight",
"id":26000000,
"maxLevel":13,
"iconUrls":{
"medium":"https:\/\/api-assets.clashroyale.com\/cards\/300\/jAj1Q5rclXxU9kVImGqSJxa4wEMfEhvwNQ_4jiGUuqg.png"
}
},
{
"name":"Archers",
"id":26000001,
"maxLevel":13,
"iconUrls":{
"medium":"https:\/\/api-assets.clashroyale.com\/cards\/300\/W4Hmp8MTSdXANN8KdblbtHwtsbt0o749BbxNqmJYfA8.png"
}
},
{
"name":"Goblins",
"id":26000002,
"maxLevel":13,
"iconUrls":{
"medium":"https:\/\/api-assets.clashroyale.com\/cards\/300\/X_DQUye_OaS3QN6VC9CPw05Fit7wvSm3XegXIXKP--0.png"
}
},
{
"name":"Giant",
"id":26000003,
"maxLevel":11,
"iconUrls":{
"medium":"https:\/\/api-assets.clashroyale.com\/cards\/300\/Axr4ox5_b7edmLsoHxBX3vmgijAIibuF6RImTbqLlXE.png"
}
}
]
}';
$array = json_decode( $json, true ); // we receive an associative array because the second parameter is true
echo $array['items'][0]['name'];
echo $array['items'][1]['id'];
Usage in for example:
$token = "token";
$url = "https://api.clashroyale.com/v1/cards";
$ch = curl_init($url);
$headr = array();
$headr[] = "Accept: application/json";
$headr[] = "Authorization: Bearer ".$token;
curl_setopt($ch, CURLOPT_HTTPHEADER, $headr);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$res = curl_exec($ch);
$data = json_decode($res, true);
curl_close($ch);
echo $data['items'][0]['name']; // echo the value of the key 'name' of the first element in items
echo $data['items'][1]['id']; // echo the value of the key 'id' of the second element in items
// you can also store them or do whatever you want
return view('clash', ['data' => $data]);
Or access the data in your view like this:
{{ $data['items'][0]['name'] }}
{{ $data['items'][0]['id'] }}

Iterate through JSON object not working in PHP

I'm trying to get data loaded from a url.
The data is given as below
{
"UFs":
[
{
"Valor" : "26.348,83",
"Fecha" : "2017-01-01"
},
{
"Valor" : "26.349,68",
"fecha" : "2017-01-02"
}
]
}
My PHP code so far looks like this:
ini_set("allow_url_fopen", 1);
$url = 'http://api.sbif.cl/api-sbifv3/recursos_api/uf/2017?apikey=472d79589e5bda11f1f032e62047911541c8a937&formato=json';
$obj = json_decode(file_get_contents($url), true);
foreach($obj as $item) {
echo $item['Valor'] . "<br/>";
}
The problem is I'm getting blank screen everytime I tried. I also tried using curl to read the url as below:
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, 'http://api.sbif.cl/api-sbifv3/recursos_api/uf/2017?apikey=472d79589e5bda11f1f032e62047911541c8a937&formato=json');
$result = curl_exec($ch);
curl_close($ch);
$obj = json_decode($result);
foreach($obj as $item) {
echo $item['Valor']."<br/>";
}
But it doesn't work either. I guess the problem is on my for each loop, or the way I'm trying to read the array.
The values are inside UFs object. Use the foreach loop this way:
foreach($obj['UFs'] as $item) {
echo $item['Valor'] . "<br/>";
}

sending multidimensional array with curl in json format

I am trying to post data using curl to a api, it has to be in JSON.
Now I have an multidimensional array that i need to pass along with the post. But i keep getting the same error all over, and i can not figure out why.
I've tried every possible way I could imagine.
This is the example that i need to send to the API:
POST /orders/ HTTP/1.1
Authorization: Basic aHVudGVyMjo=
Content-Type: application/json
{
"currency": "EUR",
"amount": 99,
"return_url": "http://www.example.com/",
"transactions": [
{
"payment_method": "ideal",
"payment_method_details": {
"issuer_id": "INGBNL2A"
}
}
]
}
So my array I made like this:
$post_fields = array();
$post_fields["currency"] = "EUR";
$post_fields["amount"] = 99;
$post_fields["return_url"] = "http://website_url.nl/return_page/";
$post_fields["transactions"]["payment_method"] = "ideal";
$post_fields["transactions"]["payment_method_details"]["issuer_id"] = "INGBNL2A";
Then the follinw i do is converting the array to a JSON string by this code:
$data_string = json_encode($post_fields);
So far is everything OK, but then i am going to post the data to the API by using the following code:
$url = "https://api.kassacompleet.nl/v1/orders/";
$curl_header = array();
$curl_header[] = "Authorization: Basic ".base64_encode("$auth_code:");
$curl_header[] = "Content-type: application/json";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $curl_header);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 180);
curl_setopt($ch, CURLOPT_TIMEOUT, 180);
$output = curl_exec($ch);
curl_close($ch);
print_r($output);
And this always results in an error that looks as the following:
{ "error": { "status": 400, "type": "", "value": "{u'payment_method': u'ideal', u'payment_method_details': {u'issuer_id': u'INGBNL2A'}} is not of type u'array'" } }
Could someone tell me where it comes from and what I am doing wrong?
Is it the format of the array or what is it?
From checking the API documentaion
It looks like transactions should be an array.
$post_fields = array();
$post_fields["currency"] = "EUR";
$post_fields["amount"] = 99;
$post_fields["return_url"] = "http://website_url.nl/return_page/";
$post_fields["transactions"][0]["payment_method"] = "ideal";
$post_fields["transactions"][1]["payment_method_details"]["issuer_id"] = "INGBNL2A";
echo '<pre>'.json_encode($post_fields).'</pre>';
/* outputs...
{
"currency":"EUR",
"amount":99,
"return_url":"http:\/\/website_url.nl\/return_page\/",
"transactions":[
{
"payment_method":"ideal",
"payment_method_details":{
"issuer_id":"INGBNL2A"
}
}
]
}
*/
I suggest that param "issuer_id" should be an array, in that case try
...
$post_fields["transactions"]["payment_method_details"]["issuer_id"] = array("INGBNL2A");
...

php JSON decode with Twitter geo/search

How do I get coordinates from twitter geo/search? There are four coordinates in the JSON tree, but the result is array. How to? Thanks.
API URL : https://api.twitter.com/1/geo/search.json?query=tokyo //での取得結果
json[result]['places']['0']['name']=Tokyo
json[result]['places']['0']['bounding_box']['type']=Polygon
json[result]['places']['0']['bounding_box']['coordinates'][0][0]=Array //Array data.
JSON tree
{
"result": {
"places": [
{
"name": "Tokyo",
"bounding_box": {
"type": "Polygon",
"coordinates": [
[
[
138.942806388889,
24.222885
],
[
142.248202222222,
24.222885
],
[
142.248202222222,
35.8986897222222
],
[
138.942806388889,
35.8986897222222
]
]
]
},
... // a long tree, something not important, hiden...
update
<?php
header('Content-type:text/html; charset=utf-8');
$url = "https://api.twitter.com/1/geo/search.json?query=tokyo";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Host: api.twitter.com'));
$body = curl_exec($ch);
curl_close ($ch);
$data = json_decode($body, true);
foreach ($data['result']['places'] as $data) {
echo $data['bounding_box']['coordinates']['0']['0'].'<br />'; //array
}
?>
If you have JSON contents, you can use json_decode() function - it'll return nice array you can read.
http://php.net/manual/en/function.json-decode.php

Categories