Access an index of multi-dimensional object in depth [duplicate] - php

This question already has answers here:
How can I access a deep object property named as a variable (dot notation) in php?
(5 answers)
Closed 4 years ago.
I have a .json configuration file. Using PHP, I'm trying to get its contents as an object by json_decode() and validate it. The JSON file contains multi-dimensional data. The problem is with accessing a member in depth dynamically.
For instance, consider the following data:
{
"somebody": {
"name": "Ali",
"age": 13,
"life": {
"stat": "good",
"happy": true
}
}
How to access the value of the following dynamically?
$happy = $data->somebody->life->happy;
What I mean from a dynamic access is something like this:
$happyIndex = "somebody->life->happy";
$happy = $data->{$happyIndex};
Also, I don't want to use eval().
Thanks.

Assuming you have a JSON data return
data="{
"somebody": {
"name": "Ali",
"age": 13,
"life": {
"stat": "good",
"happy": true
}
}"
data = jQuery.parseJSON(data);
then you can navigate to different parts of data by navigating
var name= data.somebody[0].name;
var age= data.somebody[0].age;
You will need a $.each function if you have more than one data in "somebody" array.
PHP Version:
$data='{"somebody":{"name": "Ali","age": "13","life": {"stat": "good","happy": "true"} }}';
$data = json_decode($data,TRUE);
$name= $data['somebody']['name'];
$age= $data['somebody']['age'];
echo("<pre>");
echo($name);
echo($age);
echo("</pre>");
//OUTPUT RESULT Ali 13

Related

Access JSON objects value in PHP without a loop [duplicate]

This question already has answers here:
How to find entry by object property from an array of objects?
(13 answers)
Closed 1 year ago.
I wonder how to access objects' values without a loop in a JSON file like this:
{
"adresse": "",
"longitude": "12.352",
"latitude": "61.2191",
"precision": "",
"Stats": [
{
"id": "300",
"carte_stat": "1154€",
},
{
"id": "301",
"carte_stat": "1172€",
},
{
"id": "302",
"carte_stat": "2293€",
},
],
}
I'd like to target for example the object with id '301'.
Using a loop I do like this:
foreach($result_json['Stats'] as $v) {
if ($v['id'] == "301") {
...
}
};
But How can I do without loop?
I tried things like this but in vain:
$result_json['Stats'][id='301']['carte_stat'];
$result_json['Stats']['id']->{'301'};
An alternative with array_filter.
Get the first occurence of id 301:
$json = json_decode($json, true);
$result = current(array_filter($json['Stats'], function($e) {
return $e['id'] == 301;
}));
print_r($result);
For/foreach will probably be faster. You shouldn't aim for "ligther code" when it will be a problem for readability or performance. Sometimes, more is less (problems).
You could index the Stats using array_column() to convert it. It's less efficient than a loop as it will first convert the entire array before you can access it by the id...
$stats = array_column($result_json['Stats'], "carte_stat", "id");
echo $stats['301'];
Note that I have to fix your JSON, but I assume this was due to chopping out data not needed for the question.

return single array from json by passing a value [duplicate]

This question already has answers here:
How to extract and access data from JSON with PHP?
(1 answer)
How can I get useful error messages in PHP?
(41 answers)
Closed 3 years ago.
I have a json that I need to filter a specific key and value from
the following json
{
"5": {
"Owner": "94EAC",
"Record":"0121ln"
},
"15": {
"Owner": "009AC",
"Record":"0120Pc"
},
"1": {
"Owner": "00G11A",
"Record":"000lPcn"
},
"199": {
"Owner": "00G1y9",
"Record":"01211cn"
},
"33": {
"Owner": "001AC",
"Record":"0121n"
}
}
I would like to be able to pass the first int and get back array for that number.
For example if I pass 15 I get
{
"Owner": "009AC",
"Record":"0120Pc"
}
I tried foreach loop but cannot set specific value for the first int
If I assign $data = json
then $date[15] didn't work
$data->15 also didn't work
I did also use the json decode and was able to print an array but wasn't able to get a single value
Any help would be great, I did spend all day and still cannot get an answer.
Thank you
Using Array:
$arr = json_decode($json, true);
print_r( $arr['15']);
Using Object:
$obj = json_decode($json);
print_r( $obj['15']);
Reference: json_decode

How do I access this JSON information (PHP)? [duplicate]

This question already has an answer here:
How to extract and access data from JSON with PHP?
(1 answer)
Closed 4 years ago.
I cannot access the contents within the orders array. I am currently doing this to no avail, and am wondering what I am doing wrong:
the $json object is a json response from a rest api.
$orderData = $json['orders'];
foreach($orderData['orders'] as $order){
}
{
"errors":[
],
"orders":[
{
"note":"",
"estimated_shipping_fee":"0.00",
"payment_method":"PAY_CYBERSOURCE",
"escrow_amount":"12.95",
"message_to_seller":"",
"shipping_carrier":"Singpost - Normal Mail",
"currency":"SGD",
"create_time":1532064559,
"pay_time":1532064618,
"recipient_address":{
"town":"",
"city":"",
"name":"Teo",
"district":"",
"country":"SG",
"zipcode":"41253",
"full_address":"In some street somewhjere",
"phone":"23154991",
"state":""
},
"days_to_ship":3,
"tracking_no":"",
"order_status":"SHIPPED",
"note_update_time":0,
"update_time":1532082525,
"goods_to_declare":false,
"total_amount":"12.95",
"service_code":"",
"country":"SG",
"actual_shipping_cost":"",
"cod":false,
"items":[
{
"weight":1.0,
"item_name":"ABC",
"is_wholesale":false,
"item_sku":"5123433123",
"variation_discounted_price":"12.95",
"variation_id":0,
"variation_name":"",
"item_id":1126534500,
"variation_quantity_purchased":1,
"variation_sku":"",
"variation_original_price":"12.95"
}
],
"ordersn":"3589290984539"
}
]
}
Trying to access the variables directly, by say json['orders'][0]['payment_method'] is not working.
convert it to array from json using json_decode(); then you can easily access it and if you want to access using jquery then just convert it object using jQuery.parseJSON();
just use json_decode for retrieving the object and then $obj->note or you can turn it into an array: $array = get_object_vars($obj); like in this answer .

Json 3 dimensional array to PHP [duplicate]

This question already has an answer here:
How to extract and access data from JSON with PHP?
(1 answer)
Closed 5 years ago.
i'm using Microsoft Emotion Api and it return a result as a json. so i want to access emotion values and assign that values to php variables. i used json_decode function but it can't do it.
result like below
[
{
"faceRectangle": {
"left": 63,
"top": 94,
"width": 66,
"height": 97
},
"scores": {
"anger": 0.00300731952,
"contempt": 2.18678448E-08,
"disgust": 9.284124E-06,
"fear": 0.0001912825,
"happiness": 0.9874571,
"neutral": 0.0009631537,
"sadness": 1.887755E-05,
"surprise": 0.008223598
}
}
]
You need to use this if you want it as an array
$array = json_decode($var, true);
Otherwise it will return the json as a object instead of an array
Doing this should let you access it like so:
$fl = $array[0]['faceRectangle']['left'];

PHP decode JSON get uname? [duplicate]

This question already has an answer here:
How to extract and access data from JSON with PHP?
(1 answer)
Closed 6 years ago.
How do I get the uname value from this JSON into PHP variable? to use through my page?
{
"token": "iutiutiut-0jjjjj0-97987g",
"auth": {
"id": 1,
"app_id": 1,
"user": {
"uname": "foo",
"role": "member"
}
}
}
thanks for some reason just can't get it and I can't find examples similar anywhere on google or I am not calling it correctly.
could you also tell me the correct terminology so I know as well thanks
What you're trying to do is decode JSON. PHP has a built in function for this aptly named... json_decode. Assuming your JSON is a string ($json_string), here is how you would decode it:
$obj = json_decode($json_string);
$uname = $obj->auth->user->uname;
Or, if you prefer the array syntax, use the second argument in json_decode:
$arr = json_decode($json_string, true);
$uname = $obj['auth']['user']['uname'];

Categories