Parse Json Object PHP - php

I want to parse the following Json-Object:
{"multicast_id":123456,"success":0,"failure":1,"canonical_ids":0,"results":[{"error":"InvalidRegistration"}]}
I was able to succefully parse the values from success, failure, etc, but am having difficulties getting the "error"-msg ("InvalidRegistration").
I access them like this:
$b = json_decode($a, true);
if($b['success'] == 1){
$result = true;
}
How do i access the results / error section?
I tried to do it like this:
$b['results']['error']
but it didn't work.
Thank you for your help, in advance.

After you use json_decode function, a php array will be produced that will have the following structure:
Array
(
[multicast_id] => 123456
[success] => 0
[failure] => 1
[canonical_ids] => 0
[results] => Array
(
[0] => Array
(
[error] => InvalidRegistration
)
)
)
which means that in order to access the error key inside the results array you need to type $b['results'][0]['error']. Of course, this is not the optimal way unless you know that there is always going to be one index in the results array. In the case where an unknown number of indexes existed ([0], [1], [2] ... [n]), it would be a better idea to create a loop and go through each of them.

Related

PHP using key of one array to access same key position on another array

I've looked at a number of suggestions for this, and they seem to rely on array_combine() which unfortunately is not suitable, as they arrays need to stay separate for other functions.
The arrays are set out as per
Array ( [0] => 3 [1] => 1 [2] => 3 )
Array ( [0] => 194 [1] => 0 [2] => 452 )
When I read in the first array, I get the key as $key and everything works fine.
Whenever I try and access the second array the whole script just whites out the page.
I want the code to work simliar to this ...
$a2value = $a2[$key] => $value;
echo $a2value;
Then I can do SQL lookups using $a2value
Any help would be appreciated
Here Try this
let's suppose two arrays of same number of elements
$a1=[1,2,3];
$a2=[194,0,452];
//A Simple foreach
foreach($a1 as $key=>$a1value){
$a2value=$a2[$key];
//Perform Query here
}
Remember one thing number of elements of both array should always be equal or it will cause an error
If you aren't certain about the size of both arrays then replace the line with this code
$a2value=empty($a2[$key]) ? null : $a2[$key];
Hope this works !!!

Can't extract data from Json

I can't extract data from json that I got from an api.
I tried for hours, tried all kinds of formats. Read Stackoverflow threads like How do I extract data from JSON with PHP?, but I can't see what I am doing wrong.
This is the code so far:
$api_results = '{"status":"0000","data":{"opening_price":"6998000","closing_price":"7270000","min_price":"6750000","max_price":"7997000","average_price":"7188302.5804","units_traded":"78484.9241002","volume_1day":"78484.9241002","volume_7day":"335611.84181738","buy_price":"7268000","sell_price":"7274000","date":"1510563513031"}}';
$results = json_decode($api_results, true);
// Some variations I tried:
var_dump($results->status[1]);
var_dump($results->data[1]->opening_price);
var_dump($results["data"][1]["opening_price"]);
End result: NULL NULL NULL
What am I doing wrong?
Thanks for the answers! I will upvote the working ones. Seems I got confused in the formating!
<?php
$api_results = '{"status":"0000","data":{"opening_price":"6998000","closing_price":"7270000","min_price":"6750000","max_price":"7997000","average_price":"7188302.5804","units_traded":"78484.9241002","volume_1day":"78484.9241002","volume_7day":"335611.84181738","buy_price":"7268000","sell_price":"7274000","date":"1510563513031"}}';
$results = json_decode($api_results, true);
print_r($results['status']);
echo "</br>";
print_r($results['data']['opening_price']);
Try access your array that way.
The output is :
0000
6998000
Keep an eye for the nested arrays. You need to access their parent array first in order to get their values.
Have you read the documentation of json_decode() (or, at least, the accepted answer of the question you linked)? If you pass TRUE as the second argument to json_decode() (and there is no decent reason to not pass it) then it decodes the JSON to associative arrays and not objects.
The elements in a PHP array can be accessed using the square bracket syntax.
A simple call to print_r($results) tells its structure:
Array
(
[status] => 0000
[data] => Array
(
[opening_price] => 6998000
[closing_price] => 7270000
[min_price] => 6750000
[max_price] => 7997000
[average_price] => 7188302.5804
[units_traded] => 78484.9241002
[volume_1day] => 78484.9241002
[volume_7day] => 335611.84181738
[buy_price] => 7268000
[sell_price] => 7274000
[date] => 1510563513031
)
)
Now, accessing its items is a piece of cake:
echo($results['status']);
# 0000
echo($results['data']['opening_price']);
# 6998000
Remove true from json_decode so you will have object result like Demo
$results = json_decode($api_results);
var_dump($results->status);
var_dump($results->data->opening_price);
When you use json_decode with true the returned objects will be converted into associative arrays.
Use this code like i think work it fine..
<?php
$api_results = '{"status":"0000","data":{"opening_price":"6998000","closing_price":"7270000","min_price":"6750000","max_price":"7997000","average_price":"7188302.5804","units_traded":"78484.9241002","volume_1day":"78484.9241002","volume_7day":"335611.84181738","buy_price":"7268000","sell_price":"7274000","date":"1510563513031"}}';
$results = json_decode($api_results);
print_r($results);
var_dump($results->status);
$var = $results->data;
var_dump($var->opening_price);
?>
stdClass Object
(
[status] => 0000
[data] => stdClass Object
(
[opening_price] => 6998000
[closing_price] => 7270000
[min_price] => 6750000
[max_price] => 7997000
[average_price] => 7188302.5804
[units_traded] => 78484.9241002
[volume_1day] => 78484.9241002
[volume_7day] => 335611.84181738
[buy_price] => 7268000
[sell_price] => 7274000
[date] => 1510563513031
)
)
string(4) "0000"
string(7) "6998000"
Remove true from json_decode and try something like this:
var_dump($results->status);
var_dump($results->data->opening_price);
If you see {} it is refering to objects and [] indicates that it is an array. You're trying to show everything as if they were arrays
You have set the second parameter of json_decode() to true. that means the json will be converted to an array so you are not able to access the data using pointer -> (because it is not an object).
You may access the data like this:
var_dump($results['status'][0]);
var_dump($results['data'][0]['opening_price']);
P.S: Try var_dump($results) to see the exact data, so you know how to access each attribute.

How to access stdClass Multi level object or array?

I had to make a particularly complex SOAP request in PHP and seem to have received back objects within objects. I need to get a particular value for example "session_token". I can var_dump the request and even turn it in to an array but I can't access individual elements. Please help!
Objects:
stdClass Object ( [login_response] => stdClass Object
( [response_context] => stdClass Object
( [session_token] => b1043dcb82625701188ffff03572
[response_status] => OK [response_message] => Login successful
))))
Converted array:
Array ( [0] =>
Array ( [response_context] =>
Array ( [session_token] => b1043dcb82625701188ffff03572
[response_status] => OK [response_message] => Login successful
) ) )
Once it's an array, it's JUST an array, e.g.
$obj->foo->bar->baz
will simply be
$arr['foo']['bar']['baz']
So in your case
$arr[0]['response_context']['response_status'] -> "OK"
If you leave it as an object, and there is not reason not to.
echo $obj->login_response->response_context->session_token;
echo $obj->login_response->response_context->response_status;
echo $obj->login_response->response_context->response_message;
will output
b1043dcb82625701188ffff03572
OK
Login successful
Normally to access any key of an object, need to call it like this
echo $obj->key;
But, as this is a multi-level object, to access the element, you have to code like bellow.
echo $obj->login_response->response_context->session_token;
And the result will be b1043dcb82625701188ffff03572
As same, normally to access any key of an array, need to call it like this
echo $arr['key'];
But, as this is a multi-level array, to access the element, you have to code like bellow.
echo $arr[0]['response_context']['session_token'];
And the Output is b1043dcb82625701188ffff03572
Here,
0 is the key of $arr array.
response_context is the key of 0.
session_token is the key of response_context.
You can use this service, array visualizer, this will help you target and extract only what you need. Just past the print_r output in it. That's it.
Give it a try

php foreach/for acting weirdly

Someone can solve this mystery? i have two code samples. I think that the second example does same thing as first example but apparently it doesnt.
this works:
print_r($this->facebook->my_retrieve_timeline()['data'][0]->message);
print_r($this->facebook->my_retrieve_timeline()['data'][2]->message);
this doesnt:
for ($i=0; $i <11; $i++) {
echo $this->facebook->my_retrieve_timeline()['data'][$i]->message;
}
error:
Message: Undefined property: stdClass::$message
array looks like this:
Array
(
[data] => Array
(
[0] => stdClass Object
(
[message] => bbbbbbbbb
)
[1] => stdClass Object
(
[lol] => aaaaaaaaa
)
[2] => stdClass Object
(
[message] => ccc
)
)
)
EDIT, SOLVED: so the only problem was that i didnt have message property inside of every object
Why did you think they'd be the same? The first example accesses array elements 0 and 1; the second accesses 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 and 10. Clearly at least one of those elements does not exist, given the error message you receive.
There is also a difference between print_r and echo.
Your error is because you are trying to access the object property message when it doesn't exist. Also, not an error in this case, but you are also assuming that array indexes 0-10 exist, which might not be the case.
Loop through only valid/existing array elements and check if the message property exists before accessing it:
foreach($this->facebook->my_retrieve_timeline()['data'] as $data) {
if(property_exists($data, 'message')) { // or use isset($data->message)
echo $data->message;
}
}
This doesn't make assumptions about which numeric keys exist (loops only existing elements) and also checks if message property exists before accessing it. As a bonus, it only calls my_retrieve_timeline() once instead of every loop iteration.

Array confusion with square brackets

I am using an API which has a lot of data inside lots of arrays which as you may know can be quite confusing.I am relatively new to API's and this one in particular has no documentation.
My code below is grabbing the recent_games() function which is pulling the whole API then I am using foreach loops to get inside the data.
$games = $player->recent_games();
foreach($games['gameStatistics']['array'] as $key => $gameStatistic) {
$game_date[strtotime($gameStatistic['createDate'])] = $gameStatistic;
}
// order data
krsort($game_date);
foreach ($game_date as $game => $data) {
$statistics[$data] = $data['statistics'];
}
I am getting errors such as illegal offset for:
$statistics[$data] = $data['statistics'];
Is there a way to continue down the nesting of arrays ($game_date) to get to the data that I need?
Let me know if you need more info.
Thanks
EDIT more info:
The first foreach loop at the top loops a unix timestamp key per game. Looks like this:
[1370947566] => Array
(
[skinName] => Skin_name
[ranked] => 1
[statistics] => Array
(
[array] => Array
(
[0] => Array
(
[statType] => stat_data
[value] => 1234
)
[1] => Array
(
[statType] => stat_data
[value] => 1234
)
As you can see its quite nested but I am trying to get to the individual statistics array. I hope that helps?
$statistics[$data] = $data['statistics'];
There is absolutely no way this line is correct.
The right hand side uses $data as if it were an array, indexing into it. The left hand side uses $data as a key into an array. Since the only valid types for keys are strings and integers, $data cannot satisfy the requirements of both expressions at the same time -- it cannot be an array and a string or integer.
It's obvious from the error message that $data is in fact an array, so using it as $staticstics[$data] is wrong. What do you want $statistics to be?

Categories