Access a session value - php

Here is the Print_r of a $_SESSION variable. I am trying to access the value of user_id.
Array (
[userPieUser] => loggedInUser Object (
[email] => xxxxx#hotmail.com
[hash_pw] => xxxxxxxxx
[user_id] => 3
[clean_username] => scott
[display_username] => scott
[remember_me] => [remember_me_sessid] => c13348e6d296b8d96797eed631b20ad13f58e60af00760620327b019e4773c2d6
)
)
I have tried a dozen or so ways to get that value in PHP, however no luck. such as looping through and doing if ($key = 'user_id'){ echo $value } but that just returns the first element in the array. I'm sure it is rudimentary, however appreciate the help.

The one you're looking for is:
$_SESSION['userPieUser']->user_id
As it is part of the userPieUser object.

You should try:
echo $_SESSION['userPieUser']->user_id;
fyi: There is object withing array 'userPieUser'.

Access the variable like so:
echo $_SESSION['userPieUser']['user_id'];
PHP supports accessing object indicies like this within other object indicies.

Related

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.

Issue with getting php objects from JSON array

This is the decoded array which i'm getting from url using php curl method,
Array ( [result] => Array ( [0] => Array ( [id] => 1 [name] => FIRDOUS FAROOQ BHAT [office] => MG Road [age] => 25 [start_date] => 2017-04-27 22:08:11 [salary] => $20000 ) ) )
Now the problem is i'm not able to fetch a particular value from it.I used echo $result->name; as well as var_dump['name'];,i'm getting null value. Can anyone sort it out?
if your variable name is $data where you are storing your this array,
echo $data['result'][0]['name'];
echo $data['result'][0]['office'];
or (if multiple data)
foreach($data['result'] as $res){
echo $res['name'];
echo $res['office']; //if office there
echo $res['age'];
}
You decode you json string into array, you need to use index to access array element like $result['result'][0]['name'];. You cannot use -> to access array element, this operator is used to access element of an object.
If the output you've posted here is stored in $result, you would want to access it as such:
//Get the first result, and the name from that first result
$result['result'][0]['name'];
Hello Here if result contains more than one element in array. In this case safe way to access your result is. And Here I am considering your response from CURL you will store inside $result variable if you will do it like this then below code will helps you.
foreach($result['result'] as $singleArray)
{
echo $singleArray['name'];
}
Like this you can access all elements of result array.
Here you are getting an array but you are tried to access the object,
echo $result->name;
You shouldn't use this instead use this
echo $data['result'][0]['name'];

Nested Array Foreach Issue

I am very basic new php learner, i having difficulty to get nested array value, here is my json result:
stdClass Object
(
[title] => Aao Raja - Gabbar Is Back | Chitrangada Singh
[link] => stdClass Object
(
[22] => Array
(
[0] => http://r8---sn-aigllnsk.c.docs.google.com/videoplayback?mime=video%2Fmp4&id=o-AExJcTxRDvCYsfgA1cIvQDs1v-pvLhKjTPdDh67X19vz&dur=145.542&itag=22&pl=48&ip=2a03:b0c0:1:d0::2f6:c001&sparams=dur,expire,id,ip,ipbits,itag,lmt,mime,mm,mn,ms,mv,nh,pl,ratebypass,source,upn&key=cms1&sver=3&expire=1437035009&upn=9lTw9Popb18&ratebypass=yes&source=youtube&lmt=1432539432699196&fexp=901816%2C9407809%2C9408142%2C9408420%2C9408710%2C9409172%2C9412774%2C9412846%2C9413149%2C9415664%2C9415958%2C9416126%2C9416370%2C9416656&ipbits=0&signature=3547894526817B37774A7838F8B68493CDD62101.3F143C74D76E8705800445A4CD4476C4F8BCD988&cms_redirect=yes&mm=31&mn=sn-aigllnsk&ms=au&mt=1437013301&mv=m&nh=IgpwcjAzLmxocjE0KgkxMjcuMC4wLjE&utmg=ytap1
[1] =>
[2] => hd720
)
[43] => Array
(
[0] => http://r8---sn-aigllnsk.c.docs.google.com/videoplayback?mime=video%2Fwebm&id=o-AExJcTxRDvCYsfgA1cIvQDs1v-pvLhKjTPdDh67X19vz&dur=0.000&itag=43&pl=48&ip=2a03:b0c0:1:d0::2f6:c001&sparams=dur,expire,id,ip,ipbits,itag,lmt,mime,mm,mn,ms,mv,nh,pl,ratebypass,source,upn&key=cms1&sver=3&expire=1437035009&upn=9lTw9Popb18&ratebypass=yes&source=youtube&lmt=1428933984759484&fexp=901816%2C9407809%2C9408142%2C9408420%2C9408710%2C9409172%2C9412774%2C9412846%2C9413149%2C9415664%2C9415958%2C9416126%2C9416370%2C9416656&ipbits=0&signature=266C126464ECDB4CC0FF076CD41F07BCC4DA7E34.08D9F13B7BF7D92FD1E1963336CC7FB8F19FE899&cms_redirect=yes&mm=31&mn=sn-aigllnsk&ms=au&mt=1437013301&mv=m&nh=IgpwcjAzLmxocjE0KgkxMjcuMC4wLjE&utmg=ytap1
[1] =>
[2] => medium
)
I can access the Title, but can't access the Link urls:
echo $title = $json->{'title'};
echo $link = $json->{'link'}->{'22'}->{'0'};
How can access the specific link array 22
This echo $title = $json->{'title'}; works because you are accessing an object's property and using -> is the correct way.
In this case $json->{'link'}->{'22'}->{'0'} you are trying to access an array item instead an object's property, because $json->{'link'}->{'22'} is an array and not an object. In this case, you should access it in this way: $json->{'link'}->{'22'}[0]. In order to avoid this kind of issues and, when you decode your JSON to a PHP object, you can pass true as a second parameter to the function json_decode and that will convert the whole object into an array. That way, you don't need to worry about accessing elements as object's attributes, you can access them, always, as array items. So, in this case, it would be: $json["link"]["22"][0].
You're confusing the way you access objects and arrays.
Getting the title is correct via $json->title, but the link should be $json->link->{'22'}[0] - a mixture of objects and arrays.
FYI the {'name'} notation is the same as name - only required when you are including variables in your object name e.g. {$someVar . 'name'}
I suppose you use json_decode() function. Do you know that you can get an array instead of StdClass Object? So, you can use.
<?php
$php_array = json_decode($json_string, true);

how to fetch the array values in separate variables

Array
(
[0] => Array
(
[TotalPaid] => 0
[Description] => One-time:
[PayStatus] => 0
[InvoiceTotal] => 34.78
[TotalDue] => 34.78
[JobId] => 66
[DateCreated] => 20150311T02:57:10
[Id] => 66
)
[1] => Array
(
[TotalPaid] => 0
[Description] => One-time:
[PayStatus] => 0
[InvoiceTotal] => 89.06
[TotalDue] => 89.06
[JobId] => 68
[DateCreated] => 20150311T02:58:27
[Id] => 68
)
)
i have ds array as a output this output is in a single variable ie $invoices.. i want each value in a separate variable...
When you store an array as a variable you can access each value in the array by adding the name of the array key between [] brackets after the variable name. like so...
$invoices[0]['Description']
If you wanted to loop through your invoices you could do...
foreach( $invoices as $invoice ) {
$description = $invoice['Description'];
}
If you need more info try the PHP manual - http://php.net/manual/en/language.types.array.php
EDIT: As Chris has pointed out the second example is only for use inside the loop because the example foreach would simply overwrite the variable at each iteration so you would need to do something immediately after its assignment within the iteration or it will be lost. However the first method would allow access to the value just increment the numeric key. from 0 to 1 and you would have both results assigned their own variable.
Hope that helps.
Dan
You could loop over the outer array, with a nested loop to go over the inner array. Within these, you can construct a string using the array keys (e.g. 'TotalPaid0', 'Description0', ... 'TotalPaid1', 'Description1', etc.) and then use Variable variables to store the values in.
http://php.net/manual/en/language.variables.variable.php
In response to user4501586 comment.
The code you posted to me makes no sense, you want to output to specific variables when actually to out put to that form you actually just need to call the relevant $array[0]['key'], $array[1]['key']
By this i mean select the appropriate array key and replace corresponding letter variable that you have chosen with it.
As has been suggested this is not a make me some code that works site, we are hear to help but you seem to want us to do it for you.
Also suggested. PHP Documentation you really should read up on it because i feel you do not yet grasp even the basics and that is something we cant help you with here.

Trying to print or echo an array in an array

I have an array called $results, when I use function:
print_r($results);
I get the following.
Array
(
[0] => ProfileElement Object
(
[name] => John thomson
[email] => johnt#gmail.com
[Bio] => 20 years of engineering expertise
[url] => http://twitter.com
)
)
My goal is to echo [name] [email] [Bio] [url] values separately. But when I write the following code in php I don't get any values?
echo $results[0]["ProfileElement Objects"]["Bio"];
Does anyone know why? Isn't this an array inside an array?
It appears that the array element contains an object, not another array. To access the object property, use the -> operator:
echo $results[0]->Bio;
You were close.
echo $results[0]->bio;
Is probably what you want. $result[0] is an object.
Also, depending on visibility, you may need to use a getter method.
remove ["ProfileElement Objects"]
echo $results[0]->Bio;
Try doing:
$results[0]->name;
ProfileElement Object is the object type.
It's an object inside an array. It looks like you should be able to access it as $results[0]->name, $results[0]->email, etc.
It is an object. You can get the 'Bio' value using:
echo $results[0]->Bio;

Categories