Change API Response to an array in PHP - php

I have an API which is returning me response like this.
{
"logs": [
[
"2018-05-22 00:10:16",
"Billed"
]
],
"package": "superpremium",
"subdate": "2018-05-08 14:18:18",
"submedium": "CALL"
}
I'm trying to change into array so It can be easily accessible for me. For example.
$response['subdate']; // echo 2018-05-08 14:18:18
$response['submedium']; // echo CALL
$response['package']; // echo superpremium
and the logs one should be like
$response['logs'];
logs must be an array so I can use foreach log to display all values of an array like 2018-05-22 00:10:16 or "Billed" etc
I have used below codes but returns empty screen.
json_decode($response, true);
json_decode($response);

I'm trying to change into array
Just cast it into one then:
$response = (array) json_decode($response);
After that, you can easily access $response['subdate'] etc.

Use json_decode($your_response) method. Your json data will get converted to arrays.
Like:
$response = json_decode($api_response);
And then you can access the values as (By seeing your data, seems that you are getting object):
$subdate = $response->subdate; // echo 2018-05-08 14:18:18
$submedium = $response->submedium; // echo CALL
$package = $response->package;

$json_data = json_decode($YourJSONResponse, true);
Then these will be available:
$json_data["package"]
$json_data["subdate"]
$json_data["submedium"]

Please change date from:
"submedium": "CALL",
To:
"submedium": "CALL"
Remove char "," and used function json_decode it, and enjoy

Related

How to create array from object?

I dont know what to call this array-looking object. But When I try to access elements in Php, I cant.
{
"message":"authenticated",
"data": {"id":713,"name":"Jamal","email":"abdurasulovsokhib#gmail.com","role":"user"}
}
I want to access the elements like this. $array['message']=> expecting the outcome to be "authenticated". please help
$JSON = file_get_contents('UserData.json'); // Parsing JSON from file. You can use your own way.
$Array = json_decode($JSON, true); // JSON (string) to Array
echo $Array["message"]; // Output: authenticated
echo $Array["data"]["id"]; // Output: 713

GET info from external Array/API/URL using PHP

I have the url http://pubapi.cryptsy.com/api.php?method=singleorderdata&marketid=132 which leads to an array.
I want to get the value of the first 'sellorders' which in this case is: 0.00000048 and store it in the variable $sellorderprice.
Can anyone help?
Thanks.
Just access the url contents thru file_get_contents. Your page actually return a JSON string, to get those values into meaningful data, decode it thru json_decode, after that access the data needed accordingly:
$url = 'http://pubapi.cryptsy.com/api.php?method=singleorderdata&marketid=132';
$data = json_decode(file_get_contents($url), true);
$sellorderprice = $data['return']['DOGE']['sellorders'][0]['price'];
echo $sellorderprice;
That code actually points directly to index zero 0 which gets the first price. If you need to get all items an just simply echo them all you need to iterate all items thru foreach:
foreach($data['return']['DOGE']['sellorders'] as $sellorders) {
echo $sellorders['price'], '<br/>';
}
Its simple, you just have to decode json like this:
$json = file_get_contents("http://pubapi.cryptsy.com/api.php?method=singleorderdata&marketid=132");
$arr = json_decode($json, true);
$sellorderprice = $arr['return']['DOGE']['sellorders'][0]['price'];

JSON decode with PHP: Key started with # sign

JSON is like
{
"#http_status_code": 200,
"#records_count": 200,
"warnings": [],
"query": { ... ...
In PHP
$data = json_decode($json_entry);
print $data->#http_status_code; //returns error
print $data->http_status_code; //returns nothing
How can I retrieve status code?
1) As Object way
$data = json_decode($json_entry);
print $data->{'#http_status_code'};
2) OR use as array way by passing second argument as true in json_decode
$data = json_decode($json_entry, true);
print $data['#http_status_code'];
Try json_decode to get the json in form of array ..
$json_array = json_decode($data, true);
$required_data = $data['required_key']
with reference to your particular problem .. you will get array as
Array
(
[#http_status_code] => 200
[#records_count] => 200
[warnings] => Array
(
)
....
)
so you can access you data as $data['#http_status_code']
To access an object property that has funky characters in the name, quote the name and stick it in braces.
print $data->{'#http_status_code'};
Or, say $data = json_decode($json_entry, true); to get the data back as an array.
PHP cwill give syntax error when you do this:
$data->#http_status_code;
it looks for $http_status_code variable which is not present
so in order to make this work you have to do this:
echo $data->{'#http_status_code'};
Try this:
$data = json_decode($json_entry, true);
print $data["#http_status_code"];

Processing Multidimensional JSON Array with PHP

This is the json that deepbit.net returns for my Bitcoin Miner worker. I'm trying to access the workers array and loop through to print the stats for my myemail#gmail.com worker. I can access the confirmed_reward, hashrate, ipa, and payout_history, but i'm having trouble formatting and outputting the workers array.
{
"confirmed_reward":0.11895358,
"hashrate":236.66666667,
"ipa":true,
"payout_history":0.6,
"workers":
{
"myemail#gmail.com":
{
"alive":false,
"shares":20044,
"stales":51
}
}
}
Thank you for your help :)
I assume you've decoded the string you gave with json_decode method, like...
$data = json_decode($json_string, TRUE);
To access the stats for the particular worker, just use...
$worker_stats = $data['workers']['myemail#gmail.com'];
To check whether it's alive, for example, you go with...
$is_alive = $worker_stats['alive'];
It's really that simple. )
You can use json_decode to get an associative array from the JSON string.
In your example it would look something like:
$json = 'get yo JSON';
$array = json_decode($json, true); // The `true` says to parse the JSON into an array,
// instead of an object.
foreach($array['workers']['myemail#gmail.com'] as $stat => $value) {
// Do what you want with the stats
echo "$stat: $value<br>";
}
Why don't you use json_decode.
You pass the string and it returns an object/array that you will use easily than the string directly.
To be more precise :
<?php
$aJson = json_decode('{"confirmed_reward":0.11895358,"hashrate":236.66666667,"ipa":true,"payout_history":0.6,"workers":{"myemail#gmail.com":{"alive":false,"shares":20044,"stales":51}}}');
$aJson['workers']['myemail#gmail.com']; // here's what you want!
?>
$result = json_decode($json, true); // true to return associative arrays
// instead of objects
var_dump($result['workers']['myemail#gmail.com']);

Reading multiple json values with php

I am trying to read certain values from a json string in php, I am able to do a simple json string with only one value such as
$json = '{"value":"somevalue"}';
Using this:
<?php
$json = '{"value":"somevalue"}';
$obj = json_decode(json_encode($json));
print $obj->{'value'};
?>
But when i try an get a value from the following json string it throws an error...
$json = '{"field": "title","rule": {"required": "true","minlength": "4","maxlength": "150" }}';
I validated the json on JSONlint but not sure how to access the values within this with php.
Thanks
You can try this:
$json = '{"field": "title","rule": {"required": "true","minlength": "4","maxlength": "150" }}';
//since $json is a valid json format you needn't encode and decode it again
$obj = json_decode($json);
print_r($obj->filed);
print_r($obj->rule);
You can pass true as a second parameter to json_decode() to get the results as an array
$my_arr = json_decode($json, true);
var_dump($my_arr);
Should help you. You can then step through the array as you would normally.
use var_dump to print out the object with all it's members and hierarchy. you should then be able to find the value you are looking for

Categories