Getting arraylist of json - php

I have the following Json
[response] => stdClass Object
(
[status] => 1
[httpStatus] => 200
[data] => Array
(
[0] => 230
[1] => 1956
[2] => 1958
[3] => 2294
)
How do i get the data array out of the response?
I know this is quite simple.
update
Here is some of my source code
$url = $base . http_build_query( $params );
$result = file_get_contents( $url );
echo '<pre>';
print_r( json_decode( $result ) );
echo '</pre>';
$data = $result->response->data;
print_r($data);

$json_object = json_decode($result);
print_r($json_object->response->data);
In PHP, -> is the object operator (or arrow). I'd encourage you to read more about Objects in PHP and json_decode().

That is not JSON, that is a PHP array or object. You didn't provide enough info to tell which one it is.
You can access the data array from it using either:
$data = $arr['response']->data;
Or:
$data = $obj->response->data;
Replace $arr or $obj with the actual variable name.
Edit
Your variable contains a string, because after decoding it you did not save the result. Try the following code:
$url = $base . http_build_query( $params );
$json = file_get_contents( $url );
$result = json_decode($json);
$data = $result->response->data;
echo '<pre>',print_r($data, true),'</pre>';

simply like this :-
[response] => stdClass Object
(
[status] => 1
[httpStatus] => 200
[data] => Array
(
[0] => 230
[1] => 1956
[2] => 1958
[3] => 2294
)
$json_data=json_decode($response,true);

Related

php cannot use API data

I send a request and get back JSON, so I convert that JSON to an array, but I cannot use the array with my php:
$all_transactions_raw = file_get_contents("xxx");
$all_transactions = json_decode( $all_transactions_raw );
foreach ( $all_transaction as $transaction ) {
echo $transaction;
}
First part of the very long output:
Array (
[data] => Array (
[transactions] => Array (
[0] => Array (
[id] => t1rtn-gsjkadfv
[date] => 2017-11-01
[amount] => -8847
[memo] =>
[cleared] => reconciled
[approved] => 1
[flag_color] =>
why does the above code not print a list of transactions given by the api request?
when I use print_r( $all_transactions ); I can print out a long string of what looks like an array but I cannot access the data contained in it as separate chunks. Am I missing something?
i guess you are missing these keys in foreach
$all_transactions_raw = file_get_contents("xxx");
$all_transactions = json_decode( $all_transactions_raw );
foreach ( $all_transaction['data']['transactions'] as $transaction ) {
echo $transaction;
}

Extract data from PHP curl response

My code is
$url = "URL";
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => 1
));
$result = curl_exec($curl);
var_dump($result);
$json = json_decode($result);
print_r($json);
curl_close($curl);
The response from var_dump($result) is -
string(1866) "{"status":true,"result":[{"time":"2016-11-15T19:20:27.000Z"},{"time":"2016-11-15T19:18:15.000Z"},{"time":"2016-11-15T19:15:03.000Z"},
The response I get from print_r($json) is -
stdClass Object
(
[status] => 1
[result] => Array
(
[0] => stdClass Object
(
[time] => 2016-11-15T19:20:27.000Z
)
[1] => stdClass Object
(
[time] => 2016-11-15T19:18:15.000Z
)
[2] => stdClass Object
(
[time] => 2016-11-15T19:15:03.000Z
)
I need the value of time into some variable.
Something I have done in Javscript is -
var response = JSON.parse(xmlHttpSerie.responseText);
response.forEach(function(items)
{
currentTime = items.time;
}
Can anyone tell me how do I get the value of time from the response in a variable?
echo $json['result'][0]['time'];
EDIT after major changes to the original question:
You need to use the second parameter of json_decode() to convert objects to associative arrays. Then you can use foreach() to cycle through the array and print times:
$json = json_decode($result, TRUE);
foreach ($json['result'] as $index => $v) {
echo $v['time'].'<br>';
}

get value from array - google API PHP result

I am trying to get the driving distance from google maps.
print_r($result); outputs the below:
Array
(
[0] => Array
(
[elements] => Array
(
[0] => Array
(
[distance] => Array
(
[text] => 3,936 km
[value] => 3935862
)
[duration] => Array
(
[text] => 1 day 18 hours
[value] => 150860
)
[status] => OK
)
)
)
)
my php code to produce this is:
$q = "http://maps.googleapis.com/maps/api/distancematrix/json?origins=Sydney&destinations=Perth&mode=driving&sensor=false";
$json = file_get_contents($q);
$details = json_decode($json, TRUE);
$details=$details['rows'];
print_r($details);
I somehow need to access this array and get the distance text value, in this case 3936 km
Any help appreciated,
Thanks as always
<?php
$q = "http://maps.googleapis.com/maps/api/distancematrix/json?origins=Sydney&destinations=Perth&mode=driving&sensor=false";
$json = file_get_contents($q);
$details = json_decode($json, TRUE);
$details=$details['rows'][0]['elements'][0]['distance']['text'];
print_r($details);
?>
there you go
If we assume that variable $array holds the array you have attached to your post then we can do the following:
echo $array['elements'][0]['distance']['text']; //should output 1300km
Hope it helps!

Is there a way to get facebook response in Json or array format with Facebook PHP SDK V4?

For example a request like
$request = new FacebookRequest($session, 'GET','/me/accounts?fields=id,name,access_token');
$response = $request->execute();
$arrayResult = $response->getGraphObject()->asArray();
print_r($arrayResult);
returns
Array (
[data] => Array (
[0] => stdClass Object (
[id] => 01010011100001111000111 #it's a fake id
[name] => MyAwesomePageName #And a fake name
)
)
[paging] => stdClass Object (
[next] => https://graph.facebook.com/v2.0/01010011100001111000111/accounts?fields=id,name&access_token=RanDoMAndFaaKKeEACCessToKen&limit=5000&offset=5000&__after_id=enc_IdOnOTKnoWWhAtThiSIs
)
)
Thats is.
I would like to retrieve all the response in array and without theses stdClass objects.
Just like it was in the previous version of their api.
Thanks.
An easier way might be to grab the raw JSON from the $response and decode it yourself:
$request = new FacebookRequest($session, 'GET', '/me/accounts?fields=id,name,access_token');
$response = $request->execute();
$array = json_decode($response->getRawResponse(), true);
print_r($array);
Update
As of PHP SDK 5.0+ you can use getDecodedBody() on the FacebookResponse object (this does the JSON decoding for you and returns an array).
$fb = new Facebook([...]);
$response = $fb->get('/me', '{access-token}');
$array = $response->getDecodedBody();
The Facebook SDK's asArray() method is limited as you've discovered. However, you can manually convert an object to an array using the get_object_vars( $object ); function. In your example, you can do something like:
$array = get_object_vars( $arrayResult['data'][0] );
This will convert the page Object into an array. The function isn't recursive, so you'll need to convert each object to an array.
You can use a recursive function like this:
function object_to_array($obj) {
$arr = array();
if($obj instanceOf GraphObject){
if(is_scalar($obj->asArray()) )
$arr = $obj->asArray();
else{
foreach ($obj->getPropertyNames() as $propName) {
$arr[$propName] = object_to_array($obj->getProperty($propName));
}
}
}else if(is_array($obj)){
foreach ($obj as $propKey => $propValue) {
$arr[$propKey] = object_to_array($obj[$propValue]);
}
}else $arr = $obj;
return $arr;
}
Just use json_decode($arrayResult) to get the JSON output. The output you are getting is simply a php data structure.
We can simply do json_encode and decode as an Array
$arrayResult = json_decode(json_encode($appreq['data'][0]),true);
sample output
Array
(
[application] => Array
(
[name] => Test App
[namespace] => app-test-app
[id] => 988798798798
)
[created_time] => 2015-02-17T08:42:14+0000
[data] => action=acceptit
[from] => Array
(
[id] => 987989798
[name] => TestUser
)
[message] => I have sent 1 Request
[to] => Array
(
[id] => 98098090
[name] => NameAjax
)
[id] => 345423452345_34523452453
)

Why doesn't this work?: decoding json into php array

$json = file_get_contents('outputsjson.php');
The file encodes an array then just echoes it as this (and echo $json outputs this):
{"theList":{"1":{"name":"DSC04156.JPG","title":"DSC04156.JPG","width":3264},"2":{"name":"DSC04157.JPG","title":"DSC04157.JPG","width":3264},"3":{"name":"DSC04158.JPG","title":"DSC04158.JPG","width":3264},"4":{"name":"DSC04159.JPG","title":"DSC04159.JPG","width":3264}}}
Now I'm trying to decode it from another page like this:
$myarray = json_decode($json, true);
print_r($myarray);
This outputs nothing, no errors, nothing!
Try this instead (you are mixing " and ' [single quotes instead of double quotes on the string]):
$json = '{"theList":{"1":{"name":"DSC04156.JPG","title":"DSC04156.JPG","width":3264},"2":{"name":"DSC04157.JPG","title":"DSC04157.JPG","width":3264},"3":{"name":"DSC04158.JPG","title":"DSC04158.JPG","width":3264},"4":{"name":"DSC04159.JPG","title":"DSC04159.JPG","width":3264}}} ';
$myarray = json_decode($json, true);
print_r($myarray);
And your result:
Array
(
[theList] => Array
(
[1] => Array
(
[name] => DSC04156.JPG
[title] => DSC04156.JPG
[width] => 3264
)
[2] => Array
(
[name] => DSC04157.JPG
[title] => DSC04157.JPG
[width] => 3264
)
[3] => Array
(
[name] => DSC04158.JPG
[title] => DSC04158.JPG
[width] => 3264
)
[4] => Array
(
[name] => DSC04159.JPG
[title] => DSC04159.JPG
[width] => 3264
)
)
)
Try wrapping the json string in single quotes instead of double quotes:
$json = '{"theList":{"1":{"name":"DSC04156.JPG","title":"DSC04156.JPG","width":3264},"2":{"name":"DSC04157.JPG","title":"DSC04157.JPG","width":3264},"3":{"name":"DSC04158.JPG","title":"DSC04158.JPG","width":3264},"4":{"name":"DSC04159.JPG","title":"DSC04159.JPG","width":3264}}}';
I had no problems executing the following code:
$json = '{"theList":{"1":{"name":"DSC04156.JPG","title":"DSC04156.JPG","width":3264},"2":{"name":"DSC04157.JPG","title":"DSC04157.JPG","width":3264},"3":{"name":"DSC04158.JPG","title":"DSC04158.JPG","width":3264},"4":{"name":"DSC04159.JPG","title":"DSC04159.JPG","width":3264}}}';
$myarray = json_decode($json, true);
print_r($myarray);
My guess would be that the file you are trying to read from does not exist. Remember that, if you are using Linux, file names are case-sensitive. Use the file_exists() function to check this:
var_dump(file_exists('outputsjson.php'));

Categories