How to get proper json? [duplicate] - php

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!

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

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.

PHP array return entire section [duplicate]

This question already has an answer here:
How to extract and access data from JSON with PHP?
(1 answer)
Closed 2 years ago.
Hi I am trying to get everything in within the [] brackets. I have tried everything I could find but no luck
{
"Items": [
{
"UID": "XXX-XXX",
"Code": "USD",
"CurrencyName": "US Dollar",
"CurrencyRate": 0.71428000,
"URI": "https://ar2.api.myob.com/accountright/XXX-XXX/GeneralLedger/Currency/XXX-XXX",
"RowVersion": "-6496407278109851648"
}
],
"NextPageLink": null,
"Count": 1
}
EDIT
My Code
$getsbCurrencyDetailsclass = new myobsbfunctions($_SESSION['access_token'],api_key);
$getsbCurrencyDetails = $getsbCurrencyDetailsclass->getResponsenew($cf_uri. "/GeneralLedger/Currency/?" .'$filter' ."=Code%20eq%20'{$docCurrencyType}'");
$getsbCurrencyDetails = json_decode($getsbCurrencyDetails);
$result=$getsbCurrencyDetails['Items'];
//print("<pre>".print_r($result,true)."</pre>");
echo $getsbCurrencyDetails
You need to convert the JSON into an array, then manipulate this array. Assuming the text is in $json:
$array=json_decode($json, true);
$result=$array['Items'];
EDIT
I forgot the second parameter to json_decode

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

json multiple arrays decode [duplicate]

This question already has an answer here:
How to extract and access data from JSON with PHP?
(1 answer)
Closed 6 years ago.
I have the following code:
$json = ' {
"HTML":
[
{
"id": 1,
"name": "HTML",
"match": false
},
{
"id": 2,
"name": "HTML 5",
"match": false
},
{
"id": 3,
"name": "XHTML",
"match": false
}
]
}';
$obj = json_decode($json);
$obj[0][0]->name; // JavaScript: The Definitive Guide
Why do I get the following error?
use object of type stdClass as array
I decode the json correctly, than I say that I want to pick the first object from the array (in this case HTML) and than I want to pick the name of the first one in the array.
What is going wrong?
Your first JSON is object (HTML), which contains an array of another objects. You must call ->HTML[0] (which is first object in your array) and then ->name, which is parameter of your HTML object.
$obj->HTML[0]->name;

Categories