I am attempting to work with JSON in PHP and I was wondering if someone could help me out getting me to the $events=>$url when the information is returned from json_decode. What is the variable path. There are a number of looping record in the return data and I am using something like:
$data = json_decode($feeds,true);
foreach($data as $item=>$events) {
$date = $events=>$month.'/'.$events=>$day.'/'.$events=>$year;
$events.='<li><span class="engindate">'.$date.'</span><br /><span class="source">'.$item["title"].'</span><br />'.$item["details"].'</li>';
}
Here is the JSON sample (yes, I know it is incomplete)
{
"month": 5,
"year": 2013,
"events": [
{
"url": "http://www.engin.umich.edu/college/about/cal/events/2013/may/shavuot-ends",
"id": "shavuot-ends",
"month": 5,
"year": 2013,
"day": 16,
"startTime": "1:42",
"endTime": "1:42",
"hideTime": "true",
"deadline": "true",
"am_pm": "pm",
"am_pm_start": "pm",
"am_pm_end": "pm",
"title": "Shavuot ends",
"location": "",
"details": "Shavuot runs from May 14 to May 16.",
"host": "Michigan Engineering",
"event_type": "Holiday",
"image": {
"src": "http://www.engin.umich.edu/++resource++umich_images/default_event.jpg",
"alt": "Shavuot ends"
}
},...
You have mixed up your -> and => operators. Try like this:
$data = json_decode($feeds,true);
foreach($data['events'] as $event) {
$date = $event['month'].'/'.$event['day'].'/'.$event['year'];
$events.='<li><span class="engindate">'.$date.'</span><br /><span class="source">'.$event["title"].'</span><br />'.$event["details"].'</li>';
}
$data['events']['url']
The array is multidimensional.
foreach($data as $key=>$item) {
if($key=='events') {
$url = $item['url'];
}
}
or
foreach($data['events'] as $key=>$item) {
if($key=='url') {
$url = $item;
}
}
try this:
$data = json_decode($feeds);
$eventsHtml = "";
foreach($data->events as $event ) {
$date = $data->month.'/'.$event->day.'/'.$data=>year;
$eventsHtml .='<li><span class="engindate">'.$date.
'</span><br /><span class="source">'.
$event=>title.
'</span><br /><a href="'.$event=>url.'">'.
$event->details.'</a></li>';
}
You have an object "data". This has a member "month", so this is $data->month
It has a member "events" which is an array. The first event is $data->events[0]. If you iterate with a foreach, this is foreach($data->events as $event ) { having $event as the one event.
Basic errors:
$events=>$month // is inproper syntax
foreach($data as $item=>$events) {
..
$events.= // this would overwrite the iterator variable above ??
Related
I would like to have the corresponding date of typeId: 11 output from the following JSON.
The order of the typeId's is always different, so it doesn't always work, for example, to always address the second value.
{
"page": 1,
"totalsCount": 1,
"isLastPage": true,
"lastPageNumber": 1,
"firstOnPage": 1,
"lastOnPage": 1,
"itemsPerPage": 50,
"entries": [
{
"id": 60132,
"statusName": "GIT",
"dates": [
{
"orderId": 60132,
"typeId": 7,
"date": "2021-06-03T00:00:00+02:00"
},
{
"orderId": 60132,
"typeId": 11,
"date": "2021-05-28T00:00:00+02:00"
},
{
"orderId": 60132,
"typeId": 16,
"date": "2021-05-27T20:20:28+02:00"
},
{
"orderId": 60132,
"typeId": 2,
"date": "2021-05-27T20:19:21+02:00"
},
{
"orderId": 60132,
"typeId": 4,
"date": "2021-06-03T15:16:14+02:00"
}
]
}
]
}
With my approach so far, I don't get any result:
$json = file_get_contents($orders);
$arr = json_decode($orders);
foreach($arr->entries as $order => $value) {
echo '<th scope="row">' . $value->dates->[typeId='11'].date . '</th>';
}
Where is my mistake here?
You could use array_map():
<?php
$arr = json_decode($json, true);
$result = array_filter(
array_map(
function ($record) {if($record['typeId'] == 11) return $record['date'];}, $arr['dates']
)
);
use array_filter() to remove empty values from the result-set.
working demo
EDIT
With updated json information, you could use:
$obj = json_decode($json);
foreach($obj->entries[0]->dates as $order => $value) {
if($value->typeId == 11) echo '<th scope="row">' . $value->date . '</th>';
}
working demo
For this kind of situation i usually write a simple function like this:
function getDate(array $dates, $typeId) {
foreach ($dates as $date) {
if ($date['typeId'] === $typeId) {
return $date;
}
}
return null;
}
Because the dates is an array you have to iterate over and filter out the proper elements by typeId.
Something like this:
dates.filter(({typeId}) => typeId === 11).shift().date
I have a json response like this:
{
"status": 200,
"msg": "OK",
"result": {
"folders": [
{
"id": "3812454",
"name": ".subtitles"
},
{
"id": "3812455",
"name": ".videothumb"
}
],
"files": [
{
"name": "Angamaly Diaries HD.MP4.mp4",
"cblock": null,
"sha1": "fcc2c99f2db6e3e8a700c3247206a1c2148e14cb",
"folderid": "3812453",
"upload_at": "1510255141",
"status": "active",
"size": "713544705",
"content_type": "video/mp4",
"download_count": "0",
"cstatus": "ok",
"linkextid": "PjUv5IYA2J8"
},
{
"name": "Take Off 2017.MP4.mp4",
"cblock": null,
"sha1": "2fe7fb4d45322a085d41239d6429d1cc8e94e2ce",
"folderid": "3812453",
"upload_at": "1510255141",
"status": "active",
"size": "954148848",
"content_type": "video/mp4",
"download_count": "0",
"cstatus": "ok",
"linkextid": "BIBcjWqF0_I"
},
{
"name": "Rangoon 2017 Tamil.MP4.mp4",
"cblock": null,
"sha1": "c685e7c11636982860ae7f34b671a20fc746feee",
"folderid": "3812453",
"upload_at": "1510255141",
"status": "active",
"size": "779899588",
"content_type": "video/mp4",
"download_count": "0",
"cstatus": "ok",
"linkextid": "00D7GzP6mls"
},
{
"name": "The Zookeeper’s Wife 2017.MP4.mp4.mp4",
"cblock": null,
"sha1": "a143faafbd8a6eaf2276f25cd642ac3019d71ffc",
"folderid": "3812453",
"upload_at": "1510256266",
"status": "active",
"size": "550126461",
"content_type": "video/mp4",
"download_count": "0",
"cstatus": "ok",
"linkextid": "bwUhqbiJJWQ"
}
]
}
}
And I have a string with this text:
"Watch Take Off 2017 Malayalam Full Movie Online Free"
Now I need to get the linkextid of
"name": "Take Off 2017.MP4.mp4"
from JSON response. There is one more thing that I have so much similar data on the JSON response, but I need to the get name that matches maximum words from string using PHP.
<?php
$json_data='{"status":200,"msg":"OK","result":{"folders":[{"id":"3812454","name":".subtitles"},{"id":"3812455","name":".videothumb"}],"files":[{"name":"Angamaly Diaries HD.MP4.mp4","cblock":null,"sha1":"fcc2c99f2db6e3e8a700c3247206a1c2148e14cb","folderid":"3812453","upload_at":"1510255141","status":"active","size":"713544705","content_type":"video/mp4","download_count":"0","cstatus":"ok","linkextid":"PjUv5IYA2J8"},{"name":"Take Off 2017.MP4.mp4","cblock":null,"sha1":"2fe7fb4d45322a085d41239d6429d1cc8e94e2ce","folderid":"3812453","upload_at":"1510255141","status":"active","size":"954148848","content_type":"video/mp4","download_count":"0","cstatus":"ok","linkextid":"BIBcjWqF0_I"},{"name":"Rangoon 2017 Tamil.MP4.mp4","cblock":null,"sha1":"c685e7c11636982860ae7f34b671a20fc746feee","folderid":"3812453","upload_at":"1510255141","status":"active","size":"779899588","content_type":"video/mp4","download_count":"0","cstatus":"ok","linkextid":"00D7GzP6mls"},{"name":"The Zookeeper’s Wife 2017.MP4.mp4.mp4","cblock":null,"sha1":"a143faafbd8a6eaf2276f25cd642ac3019d71ffc","folderid":"3812453","upload_at":"1510256266","status":"active","size":"550126461","content_type":"video/mp4","download_count":"0","cstatus":"ok","linkextid":"bwUhqbiJJWQ"}]}}';
$data=json_decode($json_data,true);
$files=$data['result']['files'];
$search="Watch Take Off 2017 Malayalam Full Movie Online Free";
$search_array=explode(' ',$search);
foreach($search_array as $key=>$row){
$search_array[$key]=trim($row);
}
$match=[];
foreach($files as $key=>$row){
$match_count=0;
foreach($search_array as $s){
if(preg_match('/'.$s.'/',$row['name'])){
$match_count+=1;
}
}
$match[$key]=$match_count;
}
rsort($match);
print_r($files[$match[0]]['linkextid'])
?>
Not the best solution in the world but this should work:
<?php
function compare_strings($s1, $s2) {
$s1Words = explode(' ', $s1);
$s2Words = explode(' ', $s2);
$wordCount = 0;
foreach ($s1Words as $word) {
if ( strpos($s2Words, $word) ) {
$wordCount++;
}
}
return $wordCount;
}
function get_movie_linkextid($data, $name) {
$bestMatchIndex = 1;
$bestMatchScore = 0;
foreach ($data['result']['files'] as $i => $movie) {
$currentScore = compare_strings($movie['name'], $name);
if ($currentScore > $bestMatchScore) {
$bestMatchScore = $currentScore;
$bestMatchIndex = $i;
}
}
return $data['result']['files'][$bestMatchIndex]['linkextid'];
}
$data = json_decode($yourJsonData, true);
$name = "Watch Take Off 2017 Malayalam Full Movie Online Free";
echo get_movie_linkextid($data, $name);
?>
The code just parses your JSON into a variable and than goes through all the 'files' comparing their names with the string you provided the determine the best match. After that it just return the linkextid.
I Didn't tested this code but the important is to get the idea since you will have to adapt it to be more generic anyway.
This is the JSON
{
"circuit_list": [
{
"_id": "58c0f378a986f808cdaf94cf",
"aggregation": {
"dev_name": "ME2-D2-BOO",
"port": {
"desc": "AKSES_SITE_SITE-TSEL_ME2-D2-BOO#1/2/5_200M_BOO082#CIPAKUBOO534",
"name": "1/2/5"
}
},
"area": "AREA 2",
"site_id": "N/A",
"site_name": "N/A"
},
{
"_id": "58c0f378a986f808cdaf94d0",
"aggregation": {
"dev_name": "ME2-D2-BOO",
"port": {
"desc": "AKSES_SITE_SITE-TSEL_ME2-D2-BOO#1/2/5_200M_BOO082#CIPAKUBOO534",
"name": "1/2/5"
}
},
"area": "AREA 2",
"site_id": "N/A",
"site_name": "N/A"
}
}
I already try with this code
$json = json_decode($url, true);
foreach($json as $value)
{
$_id = $value->_id;
}
it didn't work. Please help, I need to get the value to show them on the view. Did I do this wrong? this json is difficult because i didn't understand the structure.
I usually decode json with format
[{"id":"1","name":"faisal"}]
like this and with my foreach it's working.
If the second parameter of json_decode is true, the function will return an array instead of an object. Also, you would need to loop over the circuit_list property of the object.
$json = json_decode($url); // <- remove the parameter
foreach($json->circuit_list as $value) // <- loop over circuit_list
{
$_id = $value->_id;
}
<?php
$json = json_decode($url,true);
foreach($json['circuit_list'] as $value)
{
$id = $value['_id'];
}
?>
I have a code that outputs the json result below:
{
"Ghost in the Shell": {
"id": 1203,
"Pipeline": {
"id": 6144,
"name": "Pipeline",
"status": "New",
"item_id": 5962,
"TotalTasksOpen": 2
}
}
}
Now how can I format it in the my desired json format below:
Note* I have to remove some result.
{
"Ghost in the Shell":
"id": 6144,
"name": "Pipeline",
"status": "New",
"item_id": 5962,
"TotalTasksOpen": 2
}
Will appreciate if anyone can help me please.
I am not sure what is your purpose , but here is what you need
<?php
$json = '{
"Ghost in the Shell": {
"id": 1203,
"Pipeline": {
"id": 6144,
"name": "Pipeline",
"status": "New",
"item_id": 5962,
"TotalTasksOpen": 2
}
}
}';
$array = json_decode($json, true);
$newArray = array();
foreach($array as $key=>$value) {
$newArray[$key] = '';
foreach($value as $k=>$v) {
if(is_array($v)) {
$newArray = array_merge($newArray,$v);
}
}
}
$newJson = json_encode($newArray);
echo $newJson;
?>
I have a json file with a lot of records with fields for date, time and isApproved. What I am trying to do is to create a json rray that has dates for all the records that are approved. And the dates have all the hours that are booked for the current date.
So from this... :
[{"fullName":"Jojn Petkobsky","userName":"user1","phone":"12415455","email":"ees#asd.com"date":"11\/16\/2016","time":"1pm ","reason":"ReaReasonReaeason","isApproved":0,"label":"warning","status":"Approved"},{"fullName":"Zoltan Heinkelman","userName":"user2","phone":"12415455","email":"ees#asdd.com"date":"11\/16\/2016","time":"2pm ","reason":"ReaReasonReaeason","isApproved":1,"label":"warning","status":"Approved"}{"fullName":"Jojn Petkobsky","userName":"user1","phone":"12415455","email":"ees#asd.com"date":"11\/16\/2016","time":"1pm ","reason":"ReaReasonReaeason","isApproved":1,"label":"warning","status":"Approved"},{"fullName":"Frank Heinkelman","userName":"user3","phone":"12415455","email":"ees#asddd.com"date":"10\/11\/2016","time":"2pm ","reason":"ReaReasonReaeason","isApproved":1,"label":"warning","status":"Approved"}]
...i can have something like this, so i can have all the booked hours for a given date.
{"12/11/16"😞
{"time" :"10am"},
{"time" :"1pm"},
{"time" :"5pm"}
]
"12/10/16"😞
{"time" :"9am"}
]
}
I tried with something like this, but couldn't really finish it :
$string = file_get_contents("appointments.json");
$json_a = json_decode($string, true);
$date;
$datesTimes = array();
foreach($json_a as $json_r){
if ($json_r['isApproved']==1) {
$date = $json_r['date'];
//another foreach?
}
}
Any help will be appreciated!
As I mentioned in the comments, your JSON is NOT valid so I have fixed it to a point to show how it can be done.
//Fixed JSON as much as I could to show in example.
$json = '
[
{
"fullName": "Jojn Petkobsky",
"userName": "user1",
"phone": "12415455",
"email": "ees#asd.com",
"date": "11\/16\/2016",
"time": "1 pm",
"reason": "ReaReasonReaeason",
"isApproved": "0",
"label": "warning",
"status": "Approved"
},
{
"fullName": "Kitson88",
"userName": "user2",
"phone": "122323325",
"email": "eadasds#asasdasdd.com",
"date": "11\/16\/2016",
"time": "12 pm",
"reason": "ReaReasonReaeason",
"isApproved": "0",
"label": "warning",
"status": "Approved"
},
{
"fullName": "Jamie",
"userName": "user2",
"phone": "122323325",
"email": "eadasds#asasdasdd.com",
"date": "12\/16\/2016",
"time": "8 pm",
"reason": "ReaReasonReaeason",
"isApproved": "0",
"label": "warning",
"status": "Approved"
}
]
';
$array = json_decode($json, true);
//This will be you rnew Array for holding the needed data.
$approved = [];
foreach ($array as $value) {
if ($value['status'] === 'Approved') { //Any check really which will validate Approved
if (array_key_exists($value['date'], $approved)) { //Check if key exists note** will only work on 1D Array
array_push($approved[$value['date']], $value['time']); //If so, then append
} else { //If not, then create it and add value
$approved += [$value['date'] => [$value['time']]];
}
}
}
//Encode back to JSON
$newJson = json_encode($approved);
Output as JSON
{
"11\/16\/2016": ["1 pm", "12 pm"],
"12\/16\/2016": ["8 pm"]
}
http://php.net/manual/en/function.array-key-exists.php
http://php.net/manual/en/function.array-push.php