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

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.

Related

PHP array_filtered acces object [duplicate]

This question already has answers here:
PHP multidimensional array search by value
(23 answers)
Closed 14 days ago.
I'm trying to filter array from DB and I've got this postman response:
{
"1": {
"id": "3",
"key": "emails_html_body_start",
"value": "value"
}}
How I can access to id, key, value?
My code here:
$start = array_filter($array, function ($var) {
return ($var['key'] == 'emails_html_body_start');
});
echo json_encode($start);
Your question is a bit unclear ... So the upper code is what is sent by the lower code snippet? So the cho json_encode($start); is what produces the upper json data?
If so, then you obviously need to json decode that data again to be able to access a property inside that structure:
<?php
$input = <<<JSON
{
"1": {
"id": "3",
"key": "emails_html_body_start",
"value": "value"
}
}
JSON;
$data = json_decode($input, true);
$output = $data[1]['id'];
print_r($output);
The output obviously is:
3

How to see if json array contains a value? [duplicate]

This question already has answers here:
PHP multidimensional array search by value
(23 answers)
json_decode to array
(12 answers)
Closed 2 years ago.
So, I'm new to php and while testing some services, I have a JSON object:
{
"entry": [
{
"authorId": "#me",
"type": "USER"
},
{
"authorId": "514",
"type": "USER"
},
{
"authorId": "516",
"type": "USER"
}
],
"count": 3,
"totalResults": 3
}
and I need to assert that '#me' is part of this object. I tried something like:
$Obj->assertTrue(array_key_exists('#me', $response['entry']));
but it won't just work. Can someone give me a hint regarding this? Thank you
EDIT:
'#me' can be anywhere in the array, not on the first position and I'm asking this for a a test in codecept, so I need to an assert directly
You can loop through your result set to check it for each entry.
function checkEntries($object, $search) {
$object = json_decode($object, true);
foreach($object['entry'] as $entry) {
if ($entry['authorId'] == $search) {
return true;
}
}
return false;
}
Or you can use this:
PHP multidimensional array search by value

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 to get proper json? [duplicate]

This question already has answers here:
How to create an array for JSON using PHP?
(8 answers)
Closed 3 years ago.
I don't know php and JSON i wanted a result like below
How to add array employeelist on my json
{
"employeeList": [
{
"name": "Gretchen Rodriquez",
"email": "gretchenrodriquez#trasola.com"
},
{
"name": "Sharon Harris",
"email": "sharonharris#trasola.com"
},
{
"name": "Serrano Haynes",
"email": "serranohaynes#trasola.com"
}
]
}
My php code
$sql="SELECT * FROM tbl_retro_example";
$result=mysqli_query($conn, $sql);
$response=array();
while($row=mysqli_fetch_array($result))
{
array_push($response,array("name"=>$row["name"],"email"=>$row["email"]));
}
echo json_encode($response,JSON_FORCE_OBJECT);
i am getting response like below
{
"0": {
"name": "jugl",
"email": "jual#gmail.com"
},
"1": {
"name": "gond",
"email": "gond#gmail.com"
},
"2": {
"name": "kaik",
"email": "kaik#gmail.com"
}
}
How do i get proper result ?
I think you are not too far from where you need to be.
If you are looking to have your results under the employeeList key, I would change how you push the results to your array. Also, when using json_enconde you can just tell PHP which array you want to transform. For such, I would transform your:
array_push($response,array("name"=>$row["name"],"email"=>$row["email"]));
into
$response['employeeList'][] = ["name"=>$row["name"],"email"=>$row["email"]];
And, where you have:
json_encode($response,JSON_FORCE_OBJECT)
You can just do
json_encode($response);
For better output results to check your new json I would use print_r instead of echo
Give it a go and let me know how you find it :)
NOTE: I am always working under the most recent PHP version, so I tend to use [] a lot to declare my arrays. I noticed you use array() in your code example, so I am not sure if you are using an older PHP version. If such is the case and [] is not recognised yet by your version, feel free to replace it with your array declaration instead!

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

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

Categories