This question already has answers here:
How to extract and access data from JSON with PHP?
(1 answer)
How to loop through PHP object with dynamic keys [duplicate]
(16 answers)
Closed 7 years ago.
I'm new to PHP and I'm trying to use it to filter information from the New York Times' article search API. I'm still struggling to figure out how I can pull out the "web-url" and "snippet" from the JSON response even after looking through this similar question. I'm using json_decode to turn the response into an associative array. Here's my code
$data = file_get_contents($queryURL);
$jsondata = json_decode($data, true);
if (count($jsondata) != 0)
{
foreach($jsondata['response']as $key => $value)
{
echo "Key: " . $key . " Value: " . $value . " <br>";
}
}
This only prints out the words "array", "ok" and "copyright".
Here's a sample of the json:
"response": {
"meta": {
"hits": 25,
"time": 332,
"offset": 0
},
"docs": [
{
"web_url": "http://thecaucus.blogs.nytimes.com/2012/01/01/virginia-attorney-general-backs-off-ballot-proposal/",
"snippet": "Virginia's attorney general on Sunday backed off of a proposal to loosen the state's ballot access rules to allow more Republican presidential candidates to qualify.",
"lead_paragraph": "DES MOINES -- Virginia's attorney general on Sunday backed off of a proposal to loosen the state's ballot access rules to allow more Republican presidential candidates to qualify.",
"abstract": "Virginia's attorney general on Sunday backed off of a proposal to loosen the state's ballot access rules to allow more Republican presidential candidates to qualify.",
"print_page": null,
"blog": [ ],
"source": "The New York Times",
"multimedia": [ ],
"headline": {
"main": "Virginia Attorney General Backs Off Ballot Proposal",
"kicker": "The Caucus"
},
Try this. You need to loop through each of the docs
foreach ($jsondata['response']['docs'] as $doc) {
echo "web_url: " . $doc['web_url'] . " snippet: " . $doc['snippet'];
}
When you are looping through $jsondata['response']
then when your $key is meta (Similarly for other keys as well like docs etc) its $value is an array i.e
array(
"hits"=> 25,
"time"=> 332,
"offset"=> 0
)
So when you are trying to echo this $value it prints array as its a property of echo in php to print arrays as string "array".
I hope this makes clear what you are doing wrong!!!
You might need to do something like this
foreach($jsondata['response']as $key => $value)
{
// check if $jsondata['response'][$key] is an array using is_array()
// handle as per array
}
Learn about is_array
Related
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.
This question already has an answer here:
How to extract and access data from JSON with PHP?
(1 answer)
Closed 2 years ago.
I'm using Laravel. I have JSON returned from Database.
I would like to get key names like "id / name / email / revision" from following JSON.
{
"id": "000",
"records": [
{
"id": 23,
"name": "hoge",
"email": "Hoge#alk.jp",
"revision": 0
},
{
"id": 24,
"name": "zaku",
"email": "zaku#alk.jp",
"revision": 0
},
]
}
Please let me know how to get key names.
Thank you.
You should get the keys with collection get key by code following:
collect($data->records)->keys();
This will return
id
name
email
revision
More detail you can check here: https://laravel.com/docs/8.x/collections#method-keys
Use json_decode to convert it to an array:
$array = josn_decode($jsonVariable, true);
Then use foreach:
foreach($array['records'][0] as $key => $value){
$keys[] = $key;
}
or array_keys:
array_keys($array['records']);
or collect to get keys:
$keys = collect($array['records'])->keys();
I'm sorry if I don't use the correct terminology, I'm still learning. I'm trying to figure out how to search a JSON array that has nested arrays in it for a specific value, and then return an associated value.
My problem is similar to this answered question on StackOverflow (How to search through a JSON Array in PHP), but I want to be able to find an item by id in either people or dog or any other nested array. Essentially I want to convert people below in the foreach to a wildcard.
Here is my JSON data - http://foothillertech.com/student/webdesign/2018/2018benrud2/tinker/dataIntro2/test/data.json
foreach($json->people as $item)
{
if($item->id == "8097")
{
echo $item->content;
}
}
Any help is greatly appreciated.
If id is unique in the data, you can merge the inner arrays and index them by id.
$data = json_decode($json, true);
$merged = array_merge(...array_values($data));
$indexed = array_column($merged, null, 'id');
Then you can look up any of the items by id.
echo $indexed['8097']['content'] ?? 'not found';
This only works if id is unique. If not, indexing by id will result in data loss.
In this case, simply do two loops.
$json = json_decode('{
"people": [
{
"id": "8080",
"content": "foo"
},
{
"id": "8097",
"content": "bar"
}
],
"dogs": [
{
"id": "8081",
"content": "spot"
},
{
"id": "8091",
"content": "max"
}
]
}');
foreach($json as $key=>$value){
//$key = people or dogs
//$value = stdClass()
foreach($value as $item)
{
if($item->id == "8097")
{
echo $item->content;
}
}
}
Output
bar
Sandbox
If we used 8081 instead of 8097 I would expect to get 'spot`. And testing that, I do indeed get that (which is in dogs).
This question already has an answer here:
How to store column data as comma separated values when finding duplicate values in another column? [duplicate]
(1 answer)
Closed 4 years ago.
I am working with a JSON dataset provided via CSV file from my client. I have processed the CSV into a JSON format.
I have the following result (dataset reduced from 1304 to 2 for readability)
"1": {
"title": "Abercarn RFC",
"address": "High Street, Abercarn, Newport, Gwent",
"postcode": "NP11 5GQ",
"category": "Club",
"website": "http://abercarn.rfc.wales",
},
"2": {
"title": "Abercarn RFC",
"address": "High Street, Abercarn, Newport, Gwent",
"postcode": "NP11 5GQ",
"category": "Seniors",
"website": "http://abercarn.rfc.wales",
}
I want to be able to loop through my array (pre-json_encode($array)) and merge these objects but preserve both the category values into a CSV list, so the ideal output in this case will be
"category": "Club, Seniors"
I am happy to simply merge all the other fields as they are consistently the same across the data set.
You can do it with simple loop (I used the title to define similarity between element but you can change that):
$arr = array(["title" => "Abercarn RFC", "category"=> "Club"], ["title" => "other title", "category"=> "BlaBla"], ["title" => "Abercarn RFC", "category"=> "Seniors"]);
$res = array();
foreach($arr as $e) {
if (isset($res[$e["title"]]))
$res[$e["title"]]["category"] .= ", " . $e["category"];
else $res[$e["title"]] = $e;
}
If you want to remove the array key you can use array_values.
$res will be your desire output.
This question already has an answer here:
How to extract and access data from JSON with PHP?
(1 answer)
Closed last year.
How do I access an array nested inside a JSON element with PHP. Here is the code I'm using (simplified for the example), I can access from_email, html, subject etc. easily, but how would I access the to email address recipient#addresshere.co.uk? Do I need some sort of foreach loop, on the basis that there could be more than one entry?
JSON
{
"event": "inbound",
"msg": {
"dkim": {},
"email": "myemail#addresshere.co.uk",
"from_email": "example.sender#mandrillapp.com",
"headers": {},
"html": "This is an example inbound message.",
"raw_msg": "Received: from mail115.us4.mandrillapp.com",
"sender": null,
"spam_report": {},
"spf": {},
"subject": "This is an example webhook message",
"tags": [ ],
"template": null,
"text": "This is an example inbound message.",
"text_flowed": false,
"to": [
[
"recipient#addresshere.co.uk",
null
]
]
}
}
PHP
$emailp = urldecode($_REQUEST['mandrill_events']); // The above JSON
$email = array_pop(json_decode($emailp));
$from_email = $email->msg->from_email; // From email
$html = $email->msg->html; // HTML Message
$subject = $email->msg->subject; // Subject
$to = ????
Thanks
You would access the to like this
$email->msg->to[0][0];
If you want to loop around the whole array you could do
foreach ($email->msg->to[0] as $i=>$v) {
echo "i = $i and v = $v\n";
}
Or if you wanted to loop the whole to structure you could
foreach ($json->msg->to as $i=>$v) {
foreach ($v as $ii=>$vv) {
echo "ii = $ii - vv = $vv\n";
}
}
You could, as you suggest, loop through the array with foreach. For example this would echo the "to" addresses:
$to_arr = $email->msg->to[0];
foreach($to_arr as $to) {
echo 'TO = '.$to.'<br />';
}
Using true as second function parameter, objects will be converted into associative arrays.
$email = json_decode($emailp, true);
Then you can easily access any data from the array, even use foreach if needed.
print_r($email['msg']['to']);
Resuling in
Array ( [0] => Array ( [0] => recipient#addresshere.co.uk [1] => ) )
It depends on what you expect from the data. Since it's an array, it could have 0 or more elements in it. How do you plan to deal with all the cases? If you expect to only even have one, just take the first element. If you want all of the emails in an array then take the entire thing $to = $email->msg->to;.
If you're going to use this information to fire of actual emails, then yes, you do want to iterate over all the elements.
$msg = new Email();
$msg->setSubject($subject);
// more logic
foreach($recepients as $recepient) {
// assuming element 0 is email and element 1 is name
$msg->addRecepient($recepient[0], $recepient[1]);
}