check if in_array php not working - php

I want to check a value in an array. If its not there it gets pushed to a new array. If the value is already there then its not added to the new value.
But with my code the checking of the value is not working.
Its still adding the array if the specific value is present.
I got this code:
foreach($user_movie_info['data'] as $movie) {
similar_text($movie_facebook_page['genre'], $movie['genre'], $percent);
if ($percent > 30) {
echo $movie_facebook_page['genre']. "" ."</br>";
echo $movie['genre']. "" ."</br>";
echo $percent. "" ."</br>";
echo "match! </br></br>";
// add all movie information to matched array, only if its not already present
if (!in_array($movie_facebook_page['name'], $matched_movies_array)) {
array_push($matched_movies_array, $movie_facebook_page);
}
} //foreach
If i print out the $matched_movies_array i got one array 2 times in it:
Array
(
[0] => Array
(
[about] => In theaters January 4th 2013 www.TexasChainsaw3D.com
[can_post] => 1
[description] => Lionsgate’s TEXAS CHAINSAW 3D continues the legendary story of the homicidal Sawyer family, picking up where Tobe Hooper’s 1974 horror classic left off in Newt, Texas, where for decades people went missing without a trace. The townspeople long suspected the Sawyer family, owners of a local barbeque pit, were somehow responsible. Their suspicions were finally confirmed one hot summer day when a young woman escaped the Sawyer house following the brutal murders of her four friends. Word around the small town quickly spread, and a vigilante mob of enraged locals surrounded the Sawyer stronghold, burning it to the ground and killing every last member of the family – or so they thought.
Decades later and hundreds of miles away from the original massacre, a young woman named Heather learns that she has inherited a Texas estate from a grandmother she never knew she had. After embarking on a road trip with friends to uncover her roots, she finds she is the sole owner of a lavish, isolated Victorian mansion. But her newfound wealth comes at a price as she stumbles upon a horror that awaits her in the mansion’s dank cellars…
With gruesome surprises in store for a whole new generation, TEXAS CHAINSAW 3D stars Alexandra Daddario, Dan Yeager, Tremaine ‘Trey Songz’ Neverson, Scott Eastwood, Tania Raymonde, Shaun Sipos, Keram Malicki-Sanchez, James MacDonald, Thom Barry, Paul Rae and Richard Riehle, along with special appearances from four beloved cast members from previous installments of the franchise: Gunnar Hansen (the original Leatherface), Marilyn Burns, John Dugan and Bill Moseley. The film is directed by John Luessenhop (TAKERS), from a screenplay by Adam Marcus & Debra Sullivan and Kirsten Elms, based on a story by Stephen Susco and Adam Marcus & Debra Sullivan and based on characters created by Kim Henkel and Tobe Hooper, and produced by Carl Mazzocone. Lionsgate presents a production and Main Line Pictures production.
[directed_by] => John Luessenhop
[genre] => Horror
[is_published] => 1
[produced_by] => Millennium Films
[release_date] => January 4th 2012
[screenplay_by] => Adam Marcus & Debra Sullivan and Kirsten Elms
[starring] => Alexandra Daddario, Dan Yeager, Tremaine ‘Trey Songz’ Neverson, Scott Eastwood, Tania Raymonde, Shaun Sipos, Keram Malicki-Sanchez, James MacDonald, Thom Barry, Paul Rae and Richard Riehle
[studio] => Lionsgate
[talking_about_count] => 62964
[username] => TexasChainsaw3D
[website] => www.texaschainsaw3d.com, twitter.com/lionsgatehorror, http://pinterest.com/lionsgatemovies/texas-chainsaw-3d, https://plus.google.com/u/0/+LionsgateMovies, http://instagr.am/p/Qpm0JMPtDr/
[were_here_count] => 0
[written_by] => based on a story by Stephen Susco and Adam Marcus & Debra Sullivan
[category] => Movie
[id] => 323192834416509
[name] => Texas Chainsaw 3D
[link] => http://www.facebook.com/TexasChainsaw3D
[likes] => 367992
[cover] => Array
(
[cover_id] => 4.14284428641E+14
[source] => http://sphotos-c.ak.fbcdn.net/hphotos-ak-ash3/s720x720/530974_414284428640682_1806025466_n.png
[offset_y] => 0
)
)
[1] => Array
(
[about] => The official Facebook Page for The Shining | All work and no play makes Jack a dull boy.
[awards] => (1981) Saturn Award, Best Supporting Actor, Scatman Crothers
[can_post] => 1
[description] => Get The Shining at the WB Shop: http://bit.ly/shiningdvd
[directed_by] => Stanley Kubrick
[genre] => Horror, Suspense/Thriller
[is_published] => 1
[plot_outline] => All work and no play makes Academy Award-winner Jack Nicholson ("As Good As It Gets," "Batman"), the caretaker of an isolated resort, go way off the deep end, terrorizing his young son and wife Shelley Duvall ("Roxanne"). Master filmmaker Stanley Kubrick's ("Full Metal Jacket," "2001: A Space Odyssey") visually haunting chiller, based on the bestseller by master-of-suspense Stephen King ("The Stand," "Carrie," "The Shawshank Redemption"), is an undeniable contemporary classic. Newsweek Magazine calls this "the first epic horror film," full of indelible images, and a signature role for Nicholson whose character was recently selected by AFI for its' 50 Greatest Villains.
[produced_by] => Jan Harlan, Stanley Kubrick
[release_date] => 5/23/80
[screenplay_by] => Stephen King, Diane Johnson
[starring] => Jack Nicholson, Shelley Duvall, Danny Lloyd, Scatman Crothers
[studio] => Warner Bros.
[talking_about_count] => 5594
[username] => KubrickShining
[website] => http://bit.ly/shiningdvd
[were_here_count] => 0
[written_by] => Stephen King
[category] => Movie
[id] => 135347089926692
[name] => The Shining
[link] => http://www.facebook.com/KubrickShining
[likes] => 832526
[cover] => Array
(
[cover_id] => 2.24275514367E+14
[source] => http://sphotos-f.ak.fbcdn.net/hphotos-ak-ash4/320182_224275514367182_46004854_n.jpg
[offset_y] => 85
)
)
[2] => Array
(
[about] => The official Facebook Page for The Shining | All work and no play makes Jack a dull boy.
[awards] => (1981) Saturn Award, Best Supporting Actor, Scatman Crothers
[can_post] => 1
[description] => Get The Shining at the WB Shop: http://bit.ly/shiningdvd
[directed_by] => Stanley Kubrick
[genre] => Horror, Suspense/Thriller
[is_published] => 1
[plot_outline] => All work and no play makes Academy Award-winner Jack Nicholson ("As Good As It Gets," "Batman"), the caretaker of an isolated resort, go way off the deep end, terrorizing his young son and wife Shelley Duvall ("Roxanne"). Master filmmaker Stanley Kubrick's ("Full Metal Jacket," "2001: A Space Odyssey") visually haunting chiller, based on the bestseller by master-of-suspense Stephen King ("The Stand," "Carrie," "The Shawshank Redemption"), is an undeniable contemporary classic. Newsweek Magazine calls this "the first epic horror film," full of indelible images, and a signature role for Nicholson whose character was recently selected by AFI for its' 50 Greatest Villains.
[produced_by] => Jan Harlan, Stanley Kubrick
[release_date] => 5/23/80
[screenplay_by] => Stephen King, Diane Johnson
[starring] => Jack Nicholson, Shelley Duvall, Danny Lloyd, Scatman Crothers
[studio] => Warner Bros.
[talking_about_count] => 5594
[username] => KubrickShining
[website] => http://bit.ly/shiningdvd
[were_here_count] => 0
[written_by] => Stephen King
[category] => Movie
[id] => 135347089926692
[name] => The Shining
[link] => http://www.facebook.com/KubrickShining
[likes] => 832526
[cover] => Array
(
[cover_id] => 2.24275514367E+14
[source] => http://sphotos-f.ak.fbcdn.net/hphotos-ak-ash4/320182_224275514367182_46004854_n.jpg
[offset_y] => 85
)
)
)
I get this info from the open graph api from Facebook.

$matched_movies_array does not contain the movie names. So in_array will never pass.
Try something like:
$movieIds = array();
foreach($user_movie_info['data'] as $movie) {
similar_text($movie_facebook_page['genre'], $movie['genre'], $percent);
if ($percent > 30) {
echo $movie_facebook_page['genre']. "" ."</br>";
echo $movie['genre']. "" ."</br>";
echo $percent. "" ."</br>";
echo "match! </br></br>";
// add all movie information to matched array, only if its not already present
if (!in_array($movie_facebook_page['id'], $movieIds)) {
$movieIds[] = $movie_facebook_page['id'];
array_push($matched_movies_array, $movie_facebook_page);
}
} //foreach
Or maybe even better:
$id = $movie_facebook_page['id'];
if (!isset($matched_movies_array[$id])) {
$matched_movies_array[$id] = $movie_facebook_page;
}

The in_array() function doesn't work searching for a string in a multi-dimensional array. Take this for example:
$find = array("name" => "test");
$matches = array(array("name" => "test"), array("name" => "test2"));
echo (in_array($find['name'], $matches)) ? "found" : "not found";
echo "<br /><br />";
echo (in_array($find, $matches)) ? "found" : "not found";
The first echo is "not found", the second one is "found". You should use your entire $movie_facebook_page array as the needle.

Related

How to encode two arrays using json_encode?

I am using json_encode to get the JSON data but along with it I want to pass message if data is successfully passed or not that in the JSON. I am confused how to get the solution. I need only one response not two.
<?php
$url = isset($_REQUEST["url"]) ? $_REQUEST["url"] : '';
require_once dirname(__FILE__) . '/bootstrap.php';
$recipe = RecipeParser::parse(file_get_contents($url), $url);
//echo '<pre>';
//print_r($recipe);
//echo '</pre>';
if($recipe) {
$Return['status'] = 'true';
$Return['message'] = " Data found";
} else {
$Return['status'] = 'false';
$Return['message'] = "Data not found";
}
header('Content-type: application/json');
echo json_encode($recipe);
echo json_encode($return);
?>
Output of first array:
{"title":"Keto Pizza \u2013 The Best Pizza Recipe with Video \u2013 Diet Doctor","description":"","credits":"Anne Aobadia","notes":"","yield":"2 servings","source":null,"url":"https:\/\/www.dietdoctor.com\/recipes\/keto-pizza","categories":[],"photo_url":"https:\/\/i.dietdoctor.com\/wp-content\/uploads\/2016\/01\/keto_pizza_v.jpg?auto=compress%2Cformat&w=1600&h=1067&fit=crop","_parser":"StructuredData","time":{"prep":5,"cook":25,"total":30},"ingredients":[{"name":"","list":["4 eggs","11 oz. shredded cheese, preferably mozzarella or provolone","3 tbsp unsweetened tomato sauce","1 tsp dried oregano","1 1\/2 oz. pepperoni","olives (optional)","2 oz. leafy greens","4 tbsp olive oil","sea salt","ground black pepper"]}],"instructions":[{"name":"","list":["Preheat the oven to 400\u00b0F (200\u00b0C).","Start by making the crust. Crack eggs into a medium-sized bowl and add shredded cheese. Give it a good stir to combine.","Use a spatula to spread the cheese and egg batter on a baking sheet lined with parchment paper. You can form two round circles or just make one large rectangular pizza. Bake in the oven for 15 minutes until the pizza crust turns golden. Remove and let cool for a minute or two.","Increase the oven temperature to 450\u00b0F (225\u00b0C).","Spread tomato sauce on the crust and sprinkle oregano on top. Top with cheese and place the pepperoni and olives on top.","Bake for another 5-10 minutes or until the pizza has turned a golden brown color.","Serve with a fresh salad on the side."]}]}
Output of second array:
{"status":"true","message":" Data found"}
Array output:
RecipeParser_Recipe Object
(
[title] => Keto Pizza – The Best Pizza Recipe with Video – Diet Doctor
[description] =>
[credits] => Anne Aobadia
[notes] =>
[yield] => 2 servings
[source] =>
[url] => https://www.dietdoctor.com/recipes/keto-pizza
[categories] => Array
(
)
[photo_url] => https://i.dietdoctor.com/wp-content/uploads/2016/01/keto_pizza_v.jpg?auto=compress%2Cformat&w=1600&h=1067&fit=crop
[_parser] => StructuredData
[time] => Array
(
[prep] => 5
[cook] => 25
[total] => 30
)
[ingredients] => Array
(
[0] => Array
(
[name] =>
[list] => Array
(
[0] => 4 eggs
[1] => 11 oz. shredded cheese, preferably mozzarella or provolone
[2] => 3 tbsp unsweetened tomato sauce
[3] => 1 tsp dried oregano
[4] => 1 1/2 oz. pepperoni
[5] => olives (optional)
[6] => 2 oz. leafy greens
[7] => 4 tbsp olive oil
[8] => sea salt
[9] => ground black pepper
)
)
)
[instructions] => Array
(
[0] => Array
(
[name] =>
[list] => Array
(
[0] => Preheat the oven to 400°F (200°C).
[1] => Start by making the crust. Crack eggs into a medium-sized bowl and add shredded cheese. Give it a good stir to combine.
[2] => Use a spatula to spread the cheese and egg batter on a baking sheet lined with parchment paper. You can form two round circles or just make one large rectangular pizza. Bake in the oven for 15 minutes until the pizza crust turns golden. Remove and let cool for a minute or two.
[3] => Increase the oven temperature to 450°F (225°C).
[4] => Spread tomato sauce on the crust and sprinkle oregano on top. Top with cheese and place the pepperoni and olives on top.
[5] => Bake for another 5-10 minutes or until the pizza has turned a golden brown color.
[6] => Serve with a fresh salad on the side.
)
)
)
)
You have an object, so add to it or create an array that will be encoded as an object:
if($recipe) {
$recipe->return['status'] = 'true';
$recipe->return['message'] = 'Data found';
} else {
$recipe['return']['status'] = 'false';
$recipe['return']['message'] = 'Data not found';
}
header('Content-type: application/json');
echo json_encode($recipe);

Find semantics words between different phrases

I try to find a way to define in PHP a semantic by comparing some phrases and find occurence for example i have something like
Array
(
[0] => Cats love Mouse Car Dog Fish
[1] => Pictures Cats Some Text Mouse
[2] => Game of thrones 2015 Series
[3] => Stark Series lannister John Game of thrones
[4] => Pop Rock David Bowie Music
[5] => David Great Lower Text Bowie
)
And I expected for the output
Array
(
[0] => Cats Mouse
[1] => Game of thrones Series
[2] => David Bowie
)
How can I proceed ?

php sort multidimensional array on date column

I have an array $dataStoreForTableImport set up in the following way.
$dataStoreForTableImport['title']
$dataStoreForTableImport['content']
$dataStoreForTableImport['date']
$dataStoreForTableImport['link']
$dataStoreForTableImport['username']
$dataStoreForTableImport['website']
It contains data as below
Array
(
[0] => Array
(
[title] => Quote from Tony Blair
[content] => ... from beating it I'm afraid." (Tony Blair, Sky News) He had every opportunity to put religion in its ...
[articledate] => 28/09/2013
[link] => http://boards.fool.co.uk/message.asp?source=isesitlnk0000001&mid=12890951
[Username] => Michael Dray
[website] => The Motley Fool
)
[1] => Array
(
[title] => Re: The Tony Blair Show
[content] => ... I am irritated that he got such an easy ride; Why? Because he is not to your political liking? He was a witness; he was not on trial and he spoke under oath. What did you expect Jay to ask him? I had dealings with a QC a few years ago. He was as ...
[articledate] => 28/05/2012
[link] => http://boards.fool.co.uk/message.asp?source=isesitlnk0000001&mid=12564154
[Username] => Michael Dray
[website] => The Motley Fool
)
[2] => Array
(
[title] => Re: The Tony Blair Show
[content] => ... If your doubts about Jay's competence/bias were shared I'm sure it would have been debated ad nauseam on Radio 4. Eh - are you serious? I'm a Radio 4 fan - but thats despite its hatred of all things right of centre, not becuase of. ...
[articledate] => 28/05/2012
[link] => http://boards.fool.co.uk/message.asp?source=isesitlnk0000001&mid=12564167
[Username] => Michael Dray
[website] => The Motley Fool
)
[3] => Array
(
[title] => Re: The Tony Blair Show
[content] => ... Maybe Tony should have brought Cherie with him - remember Rupert Murdoch and the reaction of Wendi Deng to the custard pie incident. IMHO Cherie is every bit as intimidating:-) Wendi Deng did not eject the pie flinger, she intervened when he acted. Use of an angled bat to deflect criticism from ...
[articledate] => 30/05/2012
[link] => http://boards.fool.co.uk/message.asp?source=isesitlnk0000001&mid=12565346
[Username] => Michael Dray
[website] => The Motley Fool
)
[4] => Array
(
[title] => Re: The Tony Blair Show
[content] => ... What did surprise me was the fact that he had his own personal bodyguards in the hearing with him. Although, given the level of security that allowed that protester to break into the hearing, maybe he had a point! Eh? He is clearly at risk of terror ...
[articledate] => 28/05/2012
[link] => http://boards.fool.co.uk/message.asp?source=isesitlnk0000001&mid=12564500
[Username] => Michael Dray
[website] => The Motley Fool
)
I want to be able to remove rows from this array that if the articleDate is before a given date.
I have tried everything but it does not seem to work. I am not even able to get it to sort correctly by date?
The date comes in the format - February 10, 2007
I have used
$sortDate = date('d/m/Y', strtotime($sortDate));
to format it to the format shown in the array above.
Can anyone please help?
Thanks
Mike
Do the filtering and sorting of rows in the database backend. This will improve the performance of you app. Use a WHERE clause for filtering by date and an ORDER BY clause for ordering by date in you SQL query.

Getting Google News RSS Feeds from selected Cities

I am fetching Google news from Google News RSS feed. The URL is
http://news.google.com/news?pz=1&cf=all&ned=us&hl=en&topic=n&output=rss
This return all US titles.
[0] => Array
(
[title] => Transportation Safety Board Team Probes N.Y. Ferry Crash - Bloomberg
[link] => http://news.google.com/news/url?sa=t&fd=R&usg=AFQjCNGDVYrS8J_SXHtPWyYXxxXyKkNaRw&url=http://www.bloomberg.com/news/2013-01-10/transportation-safety-board-team-probes-n-y-ferry-crash.html
[image] => //nt3.ggpht.com/news/tbn/t9HUK7dtkbtFrM/6.jpg
[site_title] => Bloomberg
[story] => The National Transportation Safety Board began an investigation of the rush-hour commuter ferry crash near Manhattan's financial district that sent passengers flying and injured dozens. The NTSB sent an 11-member “go team†to New York yesterday to ...
)
[1] => Array
(
[title] => Obama Cabinet may not meet his own diversity standards - Los Angeles Times
[link] => http://news.google.com/news/url?sa=t&fd=R&usg=AFQjCNGSgKCy6djWVzzCkvphxbK-anvjlw&url=http://www.latimes.com/news/nationworld/nation/la-na-obama-administration-20130110,0,4200106.story
[image] => //nt2.ggpht.com/news/tbn/CtM74UExtG_E7M/6.jpg
[site_title] => Los Angeles Times
[story] => WASHINGTON — Wednesday's "photo of the day" on the White House website showed an unusual sight in Oval Office history — the president surrounded by top advisors, only half of whom are white men. The picture seemed calculated to counter criticism ...
)
[2] => Array
(
[title] => Chris Christie: Master of Disaster - TIME
[link] => http://news.google.com/news/url?sa=t&fd=R&usg=AFQjCNErxzRlmXjDZOAvqU0hMIwYspcnpg&url=http://swampland.time.com/2013/01/09/chris-christie-master-of-disaster/
[image] => //nt3.ggpht.com/news/tbn/XyB4G4Cfox0EOM/6.jpg
[site_title] => TIME
[story] => This morning on NBC's Today Show, Chris Christie reacted to being on the brand new cover of TIME. The full cover story will be available on time.com later today and on newsstands Friday. Gov. Christie was featured as one of 13 members in TIME's Class of ...
)
But I just want the news from California or XYZ. Is there a way to add a city name in parameter or any other solution? Thank you.
You need to just change value of ned and hl parameters in Url like following url you can see different news .
http://news.google.com/news?pz=1&cf=all&ned=us&hl=en&topic=n&output=rss
Spanish News
https://news.google.com/news/feeds?cf=all&ned=es_cu&hl=es&output=rss

Getting values from specified keys

i use imdb api
$homepage = file_get_contents('http://www.imdbapi.com/?i='.$imdbID);
$arr = json_decode($homepage);
In $arr i have all data about related movie.
Maguire [Year] => 1996 [Rated] => R [Released] => 13 Dec 1996 [Genre] => Comedy, Drama, Romance, Sport [Director] => Cameron Crowe [Writer] => Cameron Crowe [Actors] => Tom Cruise, Cuba Gooding Jr., Renée Zellweger, Kelly Preston [Plot] => When a sports agent has a moral epiphany and is fired for expressing it, he decides to put his new philosophy to the test as an independent with the only athlete who stays with him. [Poster] => http://ia.media-imdb.com/images/M/MV5BMTkxNjc2NjQwOF5BMl5BanBnXkFtZTcwMDE2NDU2MQ##._V1_SX320.jpg [Runtime] => 2 hrs 19 mins [Rating] => 7.2 [Votes] => 97329 [ID] => tt0116695 [Response] => True )
what i want is that reaching specified key's value.
Is there a function like that? For example , i will give the key=> Actors and get all actors?
:/ Like this?
$homepage = file_get_contents('http://www.imdbapi.com/?i='.$imdbID);
$arr = json_decode($homepage, true);
print($arr['Actors']);

Categories