php json foreach string value - php

I have a JSON file which contains some movie data:
[{
"title": "Bad Company",
"desc": "------------------------",
"rating": "6.0",
"image": "Psycho-Ex-Girlfriend-Twisted-2018.png",
"url": "master.m3u8",
"category": "اكشن"
}, {
"title": "The Pinch",
"desc": "------------------------",
"rating": "6.1",
"image": "Psycho-Ex-Girlfriend-Twisted-2018.png",
"url": "master.m3u8",
"category": "اكشن , جريمه"
}, {
"title": "Catskill Park",
"desc": "------------------------",
"rating": "6.2",
"image": "Psycho-Ex-Girlfriend-Twisted-2018.png",
"url": "master.m3u8",
"category": "خيال علمي , رعب"
}, {
"title": "Klippers",
"desc": "------------------------",
"rating": "5.3",
"image": "Psycho-Ex-Girlfriend-Twisted-2018.png",
"url": "master.m3u8",
"category": "اثاره , اكشن"
}, {
"title": "Psycho",
"desc": "------------------------",
"rating": "5.6",
"image": "Psycho-Ex-Girlfriend-Twisted-2018.png",
"url": "master.m3u8",
"category": "اثاره , دراما"
}]
I need to add all titles to a drop down menu, and when a user selects an item from the menu show the desc, image and category.
by php
Can anyone help me please?
my traying code
$url = 'http://localhost/ar.json';
$xx = json_decode(file_get_contents($url));
$data = json_decode($xx, true);
$search='title';
foreach($data['meta_data'] as $d){
if($d['key']==$search){
$found=$d['value'];
break;
}
}
echo $found?$found:"$search not found";

Assuming the structure, which you do not fully how us, is correct.
Use the key and value method of a foreach like this
$url = 'http://localhost/ar.json';
$xx = json_decode(file_get_contents($url));
$data = json_decode($xx, true);
$search='title';
$found = false;
foreach($data['meta_data'] as $key => $val){
if($key == $search){
$found = $val;
break;
}
}
echo $found ? $found : "$search not found";

Related

Jotform: Parse returned data issue

I'm trying to parse data returned by the Jotform API.
I'm successfully echoing the data but I'm also getting unnecessary additional lines of text.
My PHP code is:
include "JotForm.php";
$jotformAPI = new JotForm("myapikey");
$submissions = $jotformAPI->getFormSubmissions("myformid");
var_dump($submissions );
foreach ($submissions as $data) {
$detail = $jotformAPI->getSubmission($data['id']);
foreach ($detail as $d) {
echo $d[1]['answer']['first'] . '<br>';
}
}
result of var_dump($submissions );
{
"responseCode": 200,
"message": "success",
"content": [{
"id": "237955080346633702",
"form_id": "31751954731962",
"ip": "123.123.123.123",
"created_at": "2013-06-25 03:38:00",
"updated_at": "2013-06-27 04:58:00",
"status": "ACTIVE",
"new": "1",
"answers": {
"1": {
"text": "Name",
"type":"control_fullname",
"answer": {
"first": "LeBron",
"last": "James"
},
"prettyFormat": "LeBron James"
},
"2": {
"text": "Your Message",
"type": "control_textarea",
"answer":"¡Ay, caramba!"
}
}],
}
And here is the result I'm getting:
1
0
0
0
C
0
LeBron
I had to repair your invalid json string...
Code: (Demo)
$json = '{
"responseCode": 200,
"message": "success",
"content": [{
"id": "237955080346633702",
"form_id": "31751954731962",
"ip": "123.123.123.123",
"created_at": "2013-06-25 03:38:00",
"updated_at": "2013-06-27 04:58:00",
"status": "ACTIVE",
"new": "1",
"answers": {
"1": {
"text": "Name",
"type":"control_fullname",
"answer": {
"first": "LeBron",
"last": "James"
},
"prettyFormat": "LeBron James"
},
"2": {
"text": "Your Message",
"type": "control_textarea",
"answer":"¡Ay, caramba!"
}
}}]
}';
foreach (json_decode($json, true)['content'] as $set) {
echo "{$set['answers'][1]['answer']['first']} {$set['answers'][1]['answer']['last']}\n";
}
Output:
LeBron James
I'm a little fuzzy on the action of the jot functions, but maybe it's supposed to be like this:
foreach ($submissions as $data) {
$detail = $jotformAPI->getSubmission($data['id']);
echo $detail['answers'][1]['answer']['first'] . '<br>';
}

PHP: Loop through json comparing current time with time range based on two keys values

I'm basically trying to make an epg viewer based on some json data.
I need some help to figure out how to:
Loop through the json data.
Get the "start" and "stop" values (unix timestamps) of each program.
Make a time range for each program based on the start/stop
timestamps.
Compare the time range of each program with the current unix time.
Display the program which has a time range that fits the current time.
This is what the json data looks like:
[
{
"id": 1,
"programs": [
{
"stop": 1475982300,
"start": 1475976300,
"category": "Serier",
"id": 356532927,
"title": "Kommissær Alleyn"
},
{
"stop": 1475983500,
"start": 1475982300,
"category": "Børn",
"id": 355997207,
"title": "Udsendelsesophør"
},
{
"stop": 1475985000,
"start": 1475983500,
"id": 358595605,
"title": "DR-Friland: Frilandshaven"
},
{
"stop": 1475986800,
"start": 1475985000,
"category": "Dokumentar",
"id": 358595606,
"title": "Bonderøven 2010"
},
{
"stop": 1475989500,
"start": 1475986800,
"category": "Dokumentar",
"id": 355933560,
"title": "Made in Denmark"
},
{
"stop": 1475992500,
"start": 1475989500,
"category": "Dokumentar",
"id": 357701600,
"title": "De forunderlige dyr"
},
{
"stop": 1475995500,
"start": 1475992500,
"category": "Dokumentar",
"id": 358745047,
"title": "Italien: Fra Sardinien til Abruzzo"
},
{
"stop": 1476001200,
"start": 1475995500,
"category": "Serier",
"id": 356295670,
"title": "Mord på hjernen"
},
{
"stop": 1476004800,
"start": 1476001200,
"category": "Underholdning",
"id": 357701601,
"title": "Puk og Herman går i land - Endelave"
},
{
"stop": 1476008100,
"start": 1476004800,
"category": "Dokumentar",
"id": 355933566,
"title": "Guld på godset"
},
{
"stop": 1476011700,
"start": 1476008100,
"category": "Dokumentar",
"id": 357701602,
"title": "Guld på godset"
},
{
"stop": 1476017700,
"start": 1476011700,
"category": "Serier",
"id": 356182011,
"title": "Kriminalkommissær Barnaby"
},
{
"stop": 1476023700,
"start": 1476017700,
"category": "Sport",
"id": 358577056,
"title": "HåndboldSøndag: HC Motor Zaporozhye-TTH Holstebro (m), direkte"
},
{
"stop": 1476030600,
"start": 1476023700,
"category": "Sport",
"id": 358577057,
"title": "HåndboldSøndag: Bjerringbro Silkeborg-THW Kiel (m), direkte"
},
{
"stop": 1476032400,
"start": 1476030600,
"category": "Nyheder",
"id": 355933567,
"title": "TV AVISEN med Sporten og Vejret"
},
{
"stop": 1476032700,
"start": 1476032400,
"id": 363167503,
"title": "Guld i Købstaden - en hurtig handel"
},
{
"stop": 1476036000,
"start": 1476032700,
"category": "Dokumentar",
"id": 359619002,
"title": "Atlanterhavet: Verdens vildeste hav"
},
{
"stop": 1476039600,
"start": 1476036000,
"category": "Serier",
"id": 355933569,
"title": "Bedrag II"
},
{
"stop": 1476042000,
"start": 1476039600,
"category": "Nyheder",
"id": 355933570,
"title": "21 Søndag"
},
{
"stop": 1476042600,
"start": 1476042000,
"category": "Sport",
"id": 358745049,
"title": "Sporten"
},
{
"stop": 1476049200,
"start": 1476042600,
"category": "Film",
"id": 355933571,
"title": "Killer Elite"
},
{
"stop": 1476054600,
"start": 1476049200,
"category": "Film",
"id": 356069380,
"title": "BlackJack"
},
{
"stop": 1476060600,
"start": 1476054600,
"category": "Serier",
"id": 356069381,
"title": "Taggart: Døden checker ind"
},
{
"stop": 1476066300,
"start": 1476060600,
"category": "Film",
"id": 355933572,
"title": "Mørkets gerninger"
},
{
"stop": 1476069000,
"start": 1476066300,
"category": "Dokumentar",
"id": 362546476,
"title": "DR1 Dokumentar: Danskere omringet af IS"
}
]
}
]
This is the PHP I have so far: (I know it isn't much. I just don't know how to go on from here)
<?php
$channel = '1';
$current_unix = time();
$json = json_decode(file_get_contents('http://tvtid-app-backend.tv2.dk/api/tvtid/v1/dayviews/'.date('Y-m-d').'?ch='.$channel), true);
$programs = $json[0]['programs'];
$programs_length = count($programs);
for ($i = 0; $i < $programs_length ; $i++)
{
$begin = [$programs[$i]['start']];
$end = [$programs[$i]['stop']];
$title = [$programs[$i]['title']];
}
?>
And this how the output should look: (Example time is 16:41)
<ul>
<li class="program">
<div class="title_now">TV AVISEN med Sporten og Vejret</div>
<div class="duration_now">
<div class="now_begin">16:30</div><span class="begin">1476030600</span>
<div class="progress_bar"><div class="progress"></div></div>
<div class="now_end">17:00</div><span class="end">1476032400</span></div>
</li>
<li class="program">
<div class="title">Guld i Købstaden - en hurtig handel</div>
<div class="duration">17:00-17:05</div>
</li>
<li class="program">
<div class="title">Atlanterhavet: Verdens vildeste hav</div>
<div class="duration">17:05-18:00</div>
</li>
<li class="program">
<div class="title">Bedrag II</div>
<div class="duration">18:00-19:00</div>
</li>
etc...
</ul>
I hope this makes sense and that someone is able to help me out.
It is far simpler using foreach to process over a complete array.
$channel = '1';
$current_unix = time();
// note I have removed the TRUE option from json_decode()
$json = json_decode(file_get_contents('http://tvtid-app-backend.tv2.dk/api/tvtid/v1/dayviews/'.date('Y-m-d').'?ch='.$channel));
//print_r($json);
echo '<ul>';
foreach ($json as $data) {
echo '<li>';
foreach ($data->programs as $prog) {
if ( $current_unix < $prog->start ) {
// add your own HTML instead of the simple echo
echo $prog->title . '<br>';
echo $prog->start . '<br>';
echo $prog->stop . '<br>';
echo $prog->id . '<br>';
if ( isset($prog->category)) {
echo $prog->category . '<br>';
}
}
}
echo '</li>';
}
echo '</ul>';

Filtering JSON Object and outputting another

I'm trying to parse a JSON file which looks like this,
[
{
"id": "539eebdba276db40a4716726",
"name": "Development Task",
"idList": "539eebbb4e9a8d709704b254",
"desc": "",
"url": ""
},
{
"id": "539eebe09b42c971d46b9ba1",
"name": "Design Task",
"idList": "539eebbe50dc4fa2a82474fc",
"desc": "",
"url": ""
}
]
I'm trying to get the desc object from the array with the name Development Task, the system needs to be dynamic so I can't just use json_o[0](desc);
I've tried different methods such as foreaching the data multiple times but I still can't think of a solution, any help would be great, cheers.
Try with this:
$jsonData = '[
{
"id": "539eebdba276db40a4716726",
"name": "Development Task",
"idList": "539eebbb4e9a8d709704b254",
"desc": "",
"url": ""
},
{
"id": "539eebe09b42c971d46b9ba1",
"name": "Design Task",
"idList": "539eebbe50dc4fa2a82474fc",
"desc": "",
"url": ""
}
]';
$encoded = json_decode($jsonData);
foreach($encoded as $data)
{
if('Development Task' == $data->name)
{
echo $data->desc;
}
}
If you search for dynamic fields, i would have gone with :
$jsonData = '[
{
"id": "539eebdba276db40a4716726",
"name": "Development Task",
"idList": "539eebbb4e9a8d709704b254",
"desc": "FirstDescription",
"url": ""
},
{
"id": "539eebe09b42c971d46b9ba1",
"name": "Design Task",
"idList": "539eebbe50dc4fa2a82474fc",
"desc": "SecondDescription",
"url": ""
}
]';
$arrayFromJson = json_decode($jsonData, true);
function searchByKey($keyToSearchIn, $searchName, $array) {
foreach ($array as $key => $val) {
if ($val[$keyToSearchIn] == $searchName) {
return $val['desc'];
}
}
return null;
}
$return = searchByKey("name", "Development Task", $arrayFromJson);
So
var_dump($return);
returns
string(16) "FirstDescription"
Note : If you only need a search by name, you can change the function with :
function searchByName( $searchName, $array) {
foreach ($array as $key => $val) {
if ($val['name'] == $searchName) {
return $val['desc'];
}
}
return null;
}
$return = searchByName("Development Task", $arrayFromJson);
Hope it helps.
The comments in the code explain what happens:
$jsonData = '[
{
"id": "539eebdba276db40a4716726",
"name": "Development Task",
"idList": "539eebbb4e9a8d709704b254",
"desc": "moocow",
"url": ""
},
{
"id": "539eebe09b42c971d46b9ba1",
"name": "Design Task",
"idList": "539eebbe50dc4fa2a82474fc",
"desc": "wowcow",
"url": ""
},
{
"id": "539eebe09rb42c971d46b9ba1",
"name": "Development Task",
"idList": "539eebbe50dc4fa2a82474fc",
"desc": "sowccow",
"url": ""
}
]';
$encoded = json_decode($jsonData, true); //converts the json object to an array
foreach ($encoded as $arrayObject){
if( in_array("Development Task", $arrayObject) ){
print_r($arrayObject['desc'] . "\n");
}
}
-> moocow sowccow
based upon
I'm trying to get the desc object from the array with the name Development Task
This should do what you want and you can easily take the string and make it a variable. There are plenty of built-in functions on PHP.net that are tuned and are probably 10x better than rolling your own code.

Reading a large JSON from Facebook

How can I read several values with the same name from a JSON from Facebook, when I use this code:
$urlamandar = 'https://graph.facebook.com/'.$user."?access_token=".$access_token;
$content = file_get_contents($urlamandar);
$obj = json_decode($content, true);
$obj = json_decode($content);
It displays this:
{
"id": "XXXXXXXX",
"name": "Ricardo Capistran",
"first_name": "Ricardo",
"last_name": "Capistran",
"gender": "male",
"locale": "es_MX",
"username": "richycapy"
}
And since because there is only one ID, one NAME, one USERNAME, etc, Its quite simple place them in vars like so:
$fbuserid = $obj->{'id'};
$fbname = $obj->{'name'};
$fbusername = $obj->{'username'};
$fbemail = $obj->{'email'};
$fbbirthday = $obj->{'birthday'};
But when it comes to larger files like this code:
$urlamandar = 'https://graph.facebook.com/'.$user.'/albums?access_token='.$access_token;
Its displays a way bigger array like so:
{
"data": [
{
"id": "10150732237818223",
"from": {
"name": "Ricardo Capistran",
"id": "XXXXXXX"
},
"name": "EnterateNorte.com Photos",
"link": "https://www.facebook.com/album.php?fbid=10150732237818223&id=743158222&aid=457026",
"privacy": "custom",
"count": 31,
"type": "app",
"created_time": "2012-03-11T02:44:42+0000",
"updated_time": "2014-01-07T03:13:24+0000",
"can_upload": false
},
{
"id": "440168313222",
"from": {
"name": "Ricardo Capistran",
"id": "743158222"
},
"name": "Timeline Photos",
"link": "https://www.facebook.com/album.php?fbid=440168313222&id=743158222&aid=220377",
"cover_photo": "10151730849598223",
"privacy": "everyone",
"count": 175,
"type": "wall",
"created_time": "2010-06-30T22:38:45+0000",
"updated_time": "2014-01-01T02:09:11+0000",
"can_upload": false
},
{
"id": "10150797320378223",
"from": {
"name": "Ricardo Capistran",
"id": "743158222"
},
"name": "Instagram Photos",
"link": "https://www.facebook.com/album.php?fbid=10150797320378223&id=743158222&aid=466555",
"cover_photo": "10151695050098223",
"privacy": "friends",
"count": 37,
"type": "app",
"created_time": "2012-04-09T23:50:08+0000",
"updated_time": "2013-12-29T08:29:15+0000",
"can_upload": false
}
],
"paging": {
"cursors": {
"after": "NDM1NjY5NjI4MjIy",
"before": "MTAxNTA3MzIyMzc4MTgyMjM="
},
"next": "https://graph.facebook.com/*my_id*/albums?access_token=*access_token*&limit=25&after=NDM1NjY5NjI4MjIy"
}
}
And I would need the “name” and “id” off all the albums, so then I can repeat this same procedure with the containing pictures
Obviously it has way more albums, I just cut it after 3 just to explain my self…
Is there a way to place them in vars? With a php “for each” some how
Thanks!
You can do something like
$obj = json_decode($content, true);
$array_album = array();
foreach($obj['data'] as $key=>$val){
$array_album[] = array("id"=>$val["id"],"name"=>$val["name"]);
echo "ID : ".$val["id"]. " NAME : ".$val["name"] ;
echo "<br />";
}
print_r($array_album); // This will have all the id and names
If you dont want to store in array then the names and id will appear in the above loop and you can do whatever you want with those values. Or use the array $array_album and loop through if you want to use it later.

How would you compare the names in a list to ones in an Array?

I have a list of movies and I want to compare to the Array of movies i got from Facebook Graph API.
Here is an example of what API is getting:
{"data": [
{
"name": "The Drift Bible",
"category": "Movie",
"id": "227431881228",
"created_time": "2011-02-27T21:41:04+0000"
},
{
"name": "Shooter",
"category": "Movie",
"id": "109671005718938",
"created_time": "2011-02-16T09:18:29+0000"
}...
The list I need to compare is pretty big, but here are some:
Wall Street, Shooter, Young Guns, Due Date...
Basically just compare 'Name' in 'data' with 'my list' of Movie titles. But can't figure out the syntax
Something like:
if ($movies->data->name == 'movie titles list') {echo "You like the same movies";}
I found this:
if (in_array('movie titles list', $a)) {echo "You like the same movies";}
Any thoughts would help me out.
Thanks
The data looks to be JSON encoded...
Try something like this: (json_decode)
$large_data = '{"data": [
{
"name": "The Drift Bible",
"category": "Movie",
"id": "227431881228",
"created_time": "2011-02-27T21:41:04+0000"
},
{
"name": "Shooter",
"category": "Movie",
"id": "109671005718938",
"created_time": "2011-02-16T09:18:29+0000"
}]}';
$json_to_array = json_decode($large_data, true);
var_dump(json_decode($large_data, true));
// You should now be able to compare the two array
echo print_r($json_to_array,true);
EDIT:
Improving on what #Eric posted
$large_data = '{"data": [
{
"name": "The Drift Bible",
"category": "Movie",
"id": "227431881228",
"created_time": "2011-02-27T21:41:04+0000"
},
{
"name": "Shooter",
"category": "Movie",
"id": "109671005718938",
"created_time": "2011-02-16T09:18:29+0000"
}]}';
$movie_list = json_decode($large_data, true);
$movieNames = array();
foreach($movie_list as $movies) {
foreach($movies as $movie) {
$movieNames[] = $movie['name'];
}
}
$myMovies = array('Wall Street', 'Shooter', 'Young Guns', 'Due Date');
$common_movies = array_intersect($movieNames, $myMovies);
foreach($common_movies as $common_movie) {
echo "We like the same movie ".$common_movie."<br />\n";
}
Another method:
<?php
$json_data = '{"data": [
{
"name": "The Drift Bible",
"category": "Movie",
"id": "227431881228",
"created_time": "2011-02-27T21:41:04+0000"
},
{
"name": "Shooter",
"category": "Movie",
"id": "109671005718938",
"created_time": "2011-02-16T09:18:29+0000"
}
]}';
$array_data = json_decode($json_data, TRUE);
$compare_list = array(
'Wall Street',
'Shooter',
'Young Guns',
'Due Date'
);
// <Marco Stumper> phpundhtml at web dot de
function in_array_multi($needle, $haystack) {
$found = false;
foreach ($haystack as $value) {
if ((is_array($value) && in_array_multi($needle, $value)) || $value == $needle) {
$found = true;
}
}
return $found;
}
foreach ($compare_list as $item) {
echo '<p>' . $item . (in_array_multi($item, $array_data) ? ' DOES ' : ' does NOT ') . 'exist within $array_data</p>' . PHP_EOL;
}
?>
Output:
<p>Wall Street does NOT exist within $array_data</p>
<p>Shooter DOES exist within $array_data</p>
<p>Young Guns does NOT exist within $array_data</p>
<p>Due Date does NOT exist within $array_data</p>
Use array_intersect(array1, array2, ... arrayN)
$large_data = '{"data": [
{
"name": "The Drift Bible",
"category": "Movie",
"id": "227431881228",
"created_time": "2011-02-27T21:41:04+0000"
},
{
"name": "Shooter",
"category": "Movie",
"id": "109671005718938",
"created_time": "2011-02-16T09:18:29+0000"
}
]}';
$movies = json_decode($large_data, true)['data'];
$movieNames = array();
//Get only the name from the movie list
foreach($movies as $movie) {
$movieNames[] = $movie['name'];
}
//Intersect with internal list
print_r(array_intersect($movieNames, $myMovies));

Categories