How to parse a json in php - php

I am parsing the below json in php
{
"responseHeader":{
"status":0,
"QTime":22,
"params":{
"fl":"title,id",
"indent":"true",
"q":"einstein",
"hl.simple.pre":"<em>",
"hl.simple.post":"</em>",
"wt":"json",
"hl":"true",
"rows":"3"}},
"response":{"numFound":63,"start":0,"docs":[
{
"id":"1",
"title":"Albert Einstein"},
{
"id":"2088",
"title":"Nationalism"},
{
"id":"1551",
"title":"Dean Koontz"}]
},
"highlighting":{
"1":{
"text":[" for school exam September The Collected Papers of Albert <em>Einstein</em> Vol Doc s Unthinking for authority"]},
"2088":{
"text":[" in a letter to Alfred Kneser June Doc in The Collected Papers of Albert <em>Einstein</em> Vol Nationalism"]},
"1551":{
"text":[" changes since meeting Travis Did you get the leash on him yet <em>Einstein</em> Part Chapter Nora s query during"]}}}
using json_decode and looping through the result array I could get the individual elements in the docs section,
foreach ($myArray['response']['docs'] as $doc) {
echo $doc['id'] . "<br/>";
echo $doc['title'] . "<br/>";
}
I am now trying to figure out in getting the values from the highlighting section of this json. I want to get the text fields in the highlighting part and store it in a array.
"highlighting":{
"1":{
"text":[" for school exam September The Collected Papers of Albert <em>Einstein</em> Vol Doc s Unthinking for authority"]},
"2088":{
"text":[" in a letter to Alfred Kneser June Doc in The Collected Papers of Albert <em>Einstein</em> Vol Nationalism"]},
"1551":{
"text":[" changes since meeting Travis Did you get the leash on him yet <em>Einstein</em> Part Chapter Nora s query during"]}}}
The array should be like this,
"1" => " for school exam September The Collected Papers of Albert <em>Einstein</em> Vol Doc s Unthinking for authority"
"2088" => " in a letter to Alfred Kneser June Doc in The Collected Papers of Albert <em>Einstein</em> Vol Nationalism"
How to achieve this? Is there any way to map the id element of the docs to the number specified in the highlighting part?

You may try this (Example)
$myArray = json_decode($json, true);
$highlighting = array();
foreach($myArray['highlighting'] as $key => $value)
{
$highlighting[$key] = $value['text'][0];
}
Result :
Array (
[1] => for school exam September...
[2088] => in a letter to Alfred ...
[1551] => changes since meeting ...
)

Related

How to decode JSON event datasets?

How would I decode this JSON data to get the Location link of the event? NOTE: When I say Location I don't mean the field "location" in the json data, I am referring to the field which is in "customFields", then has a "value" which is a link to Google Maps, it also has the "type" = 9.
Problem: I am currently stuck with a page which looks like the image below, the "Notice: Undefined offset: # in...." error continues for 200 lines, because the JSON file contains the data of 200 events, the JSON included only contains the first event.
Desired Result: For the link to google maps page to be echoed on every line. I think the solution is very simple, just changing my Source code (Included) so that it can read the JSON file.
JSON dataset:
[{"eventID":152913573,"template":"Brisbane City Council","title":"Clock Tower Tour","description":"The Clock Tour Tower is a ‘must-do’ for anyone and everyone in Brisbane!<br /> <br /> For many years, City Hall’s Clock Tower made the building the tallest in Brisbane, offering visitors a magnificent 360 degree view of the city around them. Whilst the view has changed significantly over the last 90 years, the time-honoured tradition of “taking a trip up the tower” happily continues at Museum of Brisbane.<br /> <br /> The Clock Tower Tour includes a ride in one of Brisbane’s oldest working cage lifts, a look behind Australia’s largest analogue clock faces and time to explore the observation platform that shares a unique perspective of the city. See if you can catch a glimpse of the bells!<br /> <br /> <strong>Location</strong>: Tour begins from Museum of Brisbane reception on Level 3 of City Hall.","location":"Museum of Brisbane, Brisbane City","webLink":"","startDateTime":"2021-06-13T00:00:00","endDateTime":"2021-06-14T00:00:00","dateTimeFormatted":"Sunday, June 13, 2021","allDay":true,"startTimeZoneOffset":"+1000","endTimeZoneOffset":"+1000","canceled":false,"openSignUp":false,"reservationFull":false,"pastDeadline":false,"requiresPayment":false,"refundsAllowed":false,"waitingListAvailable":false,"signUpUrl":"https://eventactions.com/eareg.aspx?ea=Rsvp&invite=0tva7etjn38te1bve2yj59425pupt7wvscmr1z6depcj9ctnrh7r","repeatingRegistration":0,"repeats":"Every Sunday, Tuesday, Wednesday, Thursday, Friday and Saturday through June 30, 2021","seriesID":152913560,"eventImage":{"url":"https://www.trumba.com/i/DgDhxtvzZEBEz%2AjAEUDofPUE.jpeg","size":{"width":1290,"height":775}},"detailImage":{"url":"https://www.trumba.com/i/DgDhxtvzZEBEz%2AjAEUDofPUE.jpeg","size":{"width":1290,"height":775}},"customFields":[{"fieldID":22503,"label":"Venue","value":"Museum of Brisbane, Brisbane City","type":17},{"fieldID":22505,"label":"Venue address","value":"Museum of Brisbane, Brisbane City Hall, 64 Adelaide Street, Brisbane City","type":9},{"fieldID":21859,"label":"Event type","value":"Family events, Free","type":17},{"fieldID":22177,"label":"Cost","value":"Free","type":0},{"fieldID":23562,"label":"Age","value":"Suitable for all ages","type":0},{"fieldID":22732,"label":"Bookings","value":"Book via the Museum of Brisbane website.","type":1},{"fieldID":51540,"label":"Bookings required","value":"Yes","type":3}],"permaLinkUrl":"https://www.brisbane.qld.gov.au/trumba?trumbaEmbed=view%3devent%26eventid%3d152913573","eventActionUrl":"https://eventactions.com/eventactions/brisbane-city-council#/actions/cvuzsak1g2d45mndcjwkp24nfw","categoryCalendar":"Brisbane's calendar|Museum of Brisbane","registrationTransferTargetCount":0,"regAllowChanges":true}]
Code so far:
<?php
$output = file_get_contents("Events.json");
$decode = json_decode($output, true);
for($i = 0; $i < count($decode); $i++) {
if($decode[$i]['customFields'][$i]['type'] == 9){
echo $decode[$i]['customFields'][$i]['label'][$i]['value'];
}
echo "<br>";
}
?>
You're using the $i loop counter twice in the same expression, but the second time you use it it's pointing at non-existent elements. The snippet below 1) treats JSON objects as objects (I find it less confusing when matching code to data), and 2) uses foreach to iterate over the arrays.
I've also extracted the latitude and longitude for you into $latlong
Try this:
$decode = json_decode($json);
foreach ($decode as $event) {
foreach ($event->customFields as $field) {
if ($field->type == 9) {
echo $field->value."\n";
if (preg_match('/href="(.*?)"/', $field->value, $matches)){
preg_match('/q=([\-\.0-9]*),([\-\.0-9]*)/',$matches[1], $latlong);
array_shift($latlong);
var_dump($latlong);
}
break;
}
}
}
Output
Museum of Brisbane, Brisbane City Hall, 64 Adelaide Street, Brisbane City
array(2) {
[0]=>
string(11) "-27.4693454"
[1]=>
string(11) "153.0216909"
}
Demo:https://3v4l.org/AkRvI

json string is showing blank why is not getting decoded

i have json string but when i am getting it json_decode() it is showing blank.
$str = '[{"actcode":"Auck4","actname":"Sky Tower","date":"","time":"","timeduration":"","adult":"0","adultprice":"28","child":"0","childprice":"0","description":"Discover the best of Auckland in half a day. Soak up spectacular sights on this scenic tour, from heritage-listed buildings on Queen Street to the stunning Viaduct Harbour and panoramic vistas from the Sky Tower observation deck.
Start your tour with a hotel pick-up and travel through Auckland?s dynamic Central Business District. Travel across the iconic Auckland Harbour Bridge and admire stunning city views. Then, return to the city centre and visit the vibrant precinct of Wynyard Quarter. Here, wander among the sculptures and enjoy the happenings on the water of Viaduct Harbour.
Continue to Queen Street, also known as the ?Golden Mile? of Aucklands business and shopping district. Marvel at historic buildings like the Ferry Terminal building before visiting the Auckland Museum. Here, explore fascinating exhibits paying tribute to New Zealands natural, Maori and European histories. Afterwards, travel along Aucklands most expensive residential streets with fantastic views of the Waitemata Harbour and its islands.
Your tour ends at Sky Tower, the tallest free-standing structure in the Southern Hemisphere. Take in breathtaking 360-degree views of the city and its surroundings. In the afternoon, continue your own exploration of Auckland."}]';
i tried the below code
$array = json_decode($str,true);
echo print_r($array);
this one too
$str1 = trim($str);
$array = json_decode($str1,true);
echo print_r($array);
but the string si showing blank
try this one.
$string = mysql_real_escape_string($str);
$findsym = array('\r', '\n');
$removesym = array("", "");
$strdone = stripslashes(str_replace($findsym,$removesym,strip_tags($string)));
$jsonarray = json_decode($strdone,true);
echo "<pre>"; echo print_r($jsonarray);

Regex to isolate specific word in body of text until delimiter

I have the following specific output from which I would like to isolate from and including the word "industry" (whichever case) and the sub string until the next delimiter typically "|". I get the $output from an API So the contents of $output are always different but the generic expression may be something like: blah blah blah |industry = industry info| blah blah blah. If the word industry exists in the output I would just like to get industry = industry info. Is there a generic regex which can do this? The specific output I have returned is:
<?php
$output = '{{other uses|UBS (disambiguation)}} {{Use dmy dates|date=April
2015}} {{Infobox company |name = UBS Group AG |logo = [[File:UBS
Logo.svg|200px|UBS Group AG Logo]] |type = [[Aktiengesellschaft]]
([[Aktiengesellschaft|AG]])
[[Public company]] |traded_as = {{SWX|UBSG}} {{SWX|UBSN}}
{{nyse|UBS}} |foundation=1854 |predecessor = [[Union Bank of
Switzerland]] and [[Swiss Bank Corporation]] merged in 1998;
[[PaineWebber]] merged in 2000 |location = [[Zürich]]
[[Basel]] |key_people = [[Axel A. Weber]] (Chairman){{br}}[[Sergio
Ermotti]] (CEO) {{br}} |area_served = Worldwide |industry =[[Banking]],
[[Financial services]] |products = [[Investment Banking]]
[[Investment Management]] [[Wealth Management]] [[Private Banking]]
[[Commercial Bank|Corporate Banking]]
[[Private Equity]]
[[Finance and Insurance]]
[[Retail Banking|Consumer Banking]]
[[Mortgage loans|Mortgages]]
[[Credit Cards]] |revenue = {{Increase}} [[Swiss franc|CHF]]28.027
billion (2014) |operating_income = {{Decrease}} CHF2.461 billion (2014)
{{cite web|title=UBS Annual Report
2014|url=http://www.ubs.com/global/en/about_ubs/
investor_relations/annualreporting/2014/_jcr_content/par/
columncontrol_0/col1/linklist/link.1899571414.file/
bGluay9wYXRoPS9jb250ZW50L2RhbS9zdGF0aWMvZ2xvYmFsL2ludmV
zdG9yX3JlbGF0aW9ucy9hbm51YWwyMDE0L2FubnVhbC1yZXBv
cnQtZ3JvdXAtMjAxNC1lbi5wZGY=/annual-report-group-2014-
en.pdf|publisher=UBS.com|accessdate=May 3, 2015}}
|assets = {{Increase}} CHF1.062 trillion (2014) |equity = {{Increase}}
CHF54.368 billion (2014) |num_employees = {{Decrease}} 60,155 (2014)
|caption=We Will Not Rest |homepage = [https://www.ubs.com/ UBS.com] }}
'''UBS AG''' is a Swiss global [[financial services]] company,
incorporated in the [[Canton of Zurich]],{{cite web|title=Trade Register:
UBS AG|url=http://www.moneyhouse.ch/en/u/ubs_ag_CH-270.3.004.646-4.htm}}
and co-headquartered in [[Zürich]] and [[Basel]].{{cite
web|url=https://www.ubs.com/global/en/about_ubs/
investor_relations/faq/about.html|title=Corporate information - UBS
Global topics|work=ubs.com|accessdate=March 29, 2015}} The company
provides [[investment banking]], [[asset management]], and [[wealth
management]] services for private, corporate, and institutional clients
worldwide, and for retail clients in Switzerland as well.{{cite
web|url=https://www.ubs.com/global/en/about_ubs/
investor_relations/our_businesses.html|title=Our clients & businesses -
UBS Global topics|work=ubs.com|
accessdate=March 29, 2015}} The name ''UBS'' was originally an
abbreviation for the [[Union Bank of Switzerland]], but it ceased to be a
representational abbreviation after the bank's merger with [[Swiss Bank
Corporation]] in 1998. The company traces its origins to 1856, when the
earliest of its predecessor banks was founded.{{cite web|title=150 years
of banking tradition|url=https://www.ubs.com/global/en/about_ubs/
about_us/history/_jcr_content/rightpar/
teaser_0/linklist/link.651908116.file/
bGluay9wYXRoPS9jb250ZW50L2RhbS91YnMvZ2xvY
mFsL2Fib3V0X3Vicy9hYm91dF91cy9oaXN0b3J5X29mX3
Vicy8xNTBfeWVhcnNfb2ZfYmFua2luZ19FTkcucGRm/
150_years_of_banking_ENG.pdf|work=ubs.com|
accessdate=March 29, 2015}} UBS is the biggest
bank in Switzerland, operating in more than 50
countries with about 60,000 employees around the world, as of 2014.{{cite
web|title=About us: UBS in a few
words|url=https://www.ubs.com/global/en/
about_ubs/about_us/ourprofile.html|work=ubs.com}} It is considered the
world's largest manager of private wealth assets, with over [[Swiss
franc|CHF]]2.2 trillion in invested assets,J.P.Morgan Cazenove Europe';
?>
[^|]*\bindustry\b[^|]*
Try this.See demo.Use i flag.
https://regex101.com/r/uF4oY4/79
This will match a string which starts from after | has industry till the next |.
$re = "/[^|]*\\bindustry\\b[^|]*/i";
$str = "{{other uses|UBS (disambiguation)}} {{Use dmy dates|date=April \n2015}} {{Infobox company |name = UBS Group AG |logo = [[File:UBS \nLogo.svg|200px|UBS Group AG Logo]] |type = [[Aktiengesellschaft]] \n([[Aktiengesellschaft|AG]])\n[[Public company]] |traded_as = {{SWX|UBSG}} {{SWX|UBSN}}\n{{nyse|UBS}} |foundation=1854 |predecessor = [[Union Bank of \nSwitzerland]] and [[Swiss Bank Corporation]] merged in 1998; \n[[PaineWebber]] merged in 2000 |location = [[Zürich]]\n[[Basel]] |key_people = [[Axel A. Weber]] (Chairman){{br}}[[Sergio \nErmotti]] (CEO) {{br}} |area_served = Worldwide |industry =[[Banking]], \n[[Financial services]] |products = [[Investment Banking]]\n[[Investment Management]] [[Wealth Management]] [[Private Banking]]\n[[Commercial Bank|Corporate Banking]]\n[[Private Equity]]\n[[Finance and Insurance]]\n[[Retail Banking|Consumer Banking]]\n[[Mortgage loans|Mortgages]]\n[[Credit Cards]] |revenue = {{Increase}} [[Swiss franc|CHF]]28.027 \nbillion (2014) |operating_income = {{Decrease}} CHF2.461 billion (2014) \n{{cite web|title=UBS Annual Report \n2014|url=http://www.ubs.com/global/en/about_ubs/\ninvestor_relations/annualreporting/2014/_jcr_content/par/\ncolumncontrol_0/col1/linklist/link.1899571414.file/\nbGluay9wYXRoPS9jb250ZW50L2RhbS9zdGF0aWMvZ2xvYmFsL2ludmV\nzdG9yX3JlbGF0aW9ucy9hbm51YWwyMDE0L2FubnVhbC1yZXBv\ncnQtZ3JvdXAtMjAxNC1lbi5wZGY=/annual-report-group-2014- \nen.pdf|publisher=UBS.com|accessdate=May 3, 2015}} \n|assets = {{Increase}} CHF1.062 trillion (2014) |equity = {{Increase}} \nCHF54.368 billion (2014) |num_employees = {{Decrease}} 60,155 (2014) \n|caption=We Will Not Rest |homepage = [https://www.ubs.com/ UBS.com] }} \n'''UBS AG''' is a Swiss global [[financial services]] company, \nincorporated in the [[Canton of Zurich]],{{cite web|title=Trade Register: \nUBS AG|url=http://www.moneyhouse.ch/en/u/ubs_ag_CH-270.3.004.646-4.htm}} \nand co-headquartered in [[Zürich]] and [[Basel]].{{cite \nweb|url=https://www.ubs.com/global/en/about_ubs/\ninvestor_relations/faq/about.html|title=Corporate information - UBS \nGlobal topics|work=ubs.com|accessdate=March 29, 2015}} The company \nprovides [[investment banking]], [[asset management]], and [[wealth \nmanagement]] services for private, corporate, and institutional clients \nworldwide, and for retail clients in Switzerland as well.{{cite \nweb|url=https://www.ubs.com/global/en/about_ubs/\ninvestor_relations/our_businesses.html|title=Our clients & businesses - \nUBS Global topics|work=ubs.com|\naccessdate=March 29, 2015}} The name ''UBS'' was originally an \nabbreviation for the [[Union Bank of Switzerland]], but it ceased to be a \nrepresentational abbreviation after the bank's merger with [[Swiss Bank \nCorporation]] in 1998. The company traces its origins to 1856, when the \nearliest of its predecessor banks was founded.{{cite web|title=150 years \nof banking tradition|url=https://www.ubs.com/global/en/about_ubs/\nabout_us/history/_jcr_content/rightpar/\nteaser_0/linklist/link.651908116.file/\nbGluay9wYXRoPS9jb250ZW50L2RhbS91YnMvZ2xvY\nmFsL2Fib3V0X3Vicy9hYm91dF91cy9oaXN0b3J5X29mX3\nVicy8xNTBfeWVhcnNfb2ZfYmFua2luZ19FTkcucGRm/\n150_years_of_banking_ENG.pdf|work=ubs.com|\naccessdate=March 29, 2015}} UBS is the biggest\nbank in Switzerland, operating in more than 50 \ncountries with about 60,000 employees around the world, as of 2014.{{cite \nweb|title=About us: UBS in a few \nwords|url=https://www.ubs.com/global/en/\nabout_ubs/about_us/ourprofile.html|work=ubs.com}} It is considered the \nworld's largest manager of private wealth assets, with over [[Swiss \nfranc|CHF]]2.2 trillion in invested assets,J.P.Morgan Cazenove Europ";
preg_match_all($re, $str, $matches);
I would not apply a regex on a large input string like yours. As you can see in the regex debugger, vks' regex makes about 340,000 steps to finally fetch you a result.
I suggest splitting the string with | first, and then grepping out the info you need.
$chks = explode("|", $output);
foreach ($chks as $chk) {
if (strpos($chk,'industry =') !== false) {
echo $chk;
}
}
Result:
industry =[[Banking]],
[[Financial services]]
See IDEONE demo

How to create csv file using raw text data

i am much confused at this point regarding the csv file creation and insert data in the database.
suppose i have below text data - that is of 45000 record set, i am posting dew of them below.
Winged Wheels in France, by Michael Myers Shoemaker 45790
A Battle Fought on Snow Shoes, by Mary Cochrane Rogers 45789
The German Classics of the Nineteenth and Twentieth Centuries, 45788
Volume 11, by Friedrich Spielhagen, Theodor Storm,
Wilhelm Raabe, Marion D. Learned and Ewald Eiserhardt
[Subtitle: Masterpieces of German Literature
Translated Into English]
Zofloya ou le Maure, Tomes 1-4, by Charlotte Dacre 45787
[Subtitle: Histoire du XVe si?cle]
[Language: French]
Their Majesties as I Knew Them, by Xavier Paoli 45786
[Subtitle: Personal Reminiscences of the
Kings and Queens of Europe]
[Translator: Alexander Teixeira de Mattos]
New York Times Current History: The European War, Vol. 8, 45785
Pt. 2, No. 1, July 1918, by Various
Gallery of Comicalities, by Robert Cruikshank, 45784
George Cruikshank and Robert Seymour
[Subtitle: Embracing Humorous Sketches]
Katri, by Emil Nervander 45783
[Subtitle: Kertomus 17 vuosi-sadasta]
[Language: Finnish]
The Little Brown Jug at Kildare, by Meredith Nicholson 45782
[Illustrator: James Montgomery Flagg]
Beaumont & Fletcher's Works (6 through 10), by Francis Beaumont 45781
and John Fletcher
[Subtitle: The Queen of Corinth; Bonduca; The Knight of the
Burning Pestle; Loves Pilgrimage; The Double Marriage]
Beaumont & Fletcher's Works (1 through 5), by Francis Beaumont 45780
and John Fletcher
[Subtitle: A Wife for a Month; The Lovers Progress;
The Pilgrim; The Captain; The Prophetess]
The Washington Historical Quarterly, Volume V, 1914, by Various 45779
[Editor: Edmond S. Meany]
Minstrelsy of the Scottish Border Volume III of 3, by Walter Scott 45778
[Subtitle: Consisting of Historical and Romantic Ballads,
Collected In the Southern Counties of Scotland; With
a Few Of Modern Date, Founded Upon Local Tradition.
In Three Volumes. Vol. III]
What i want is simply insert Winged Wheels in France, by Michael Myers Shoemaker in one column and 45790 in other column of CSV. then i will be able to add them to my database.
moreover, e.g,
The German Classics of the Nineteenth and Twentieth Centuries,
Volume 11, by Friedrich Spielhagen, Theodor Storm,
Wilhelm Raabe, Marion D. Learned and Ewald Eiserhardt
[Subtitle: Masterpieces of German Literature
Translated Into English]
i want to insert above text in this way:
The German Classics of the Nineteenth and Twentieth Centuries,
Volume 11, by Friedrich Spielhagen, Theodor Storm,
Wilhelm Raabe, Marion D. Learned and Ewald Eiserhardt
means no this portion:
[Subtitle: Masterpieces of German Literature
Translated Into English]
the ", by" should also omitted and so my new data would be like this. so actually i need three columns in the csv.
1 | Winged Wheels in France | Michael Myers Shoemaker | 45790
2 | The German Classics of the Nineteenth and Twentieth Centuries,
Volume 11 | Friedrich Spielhagen, Theodor Storm,
Wilhelm Raabe, Marion D. Learned and Ewald Eiserhardt | 45789
Please help in getting it inserted in excel file and create csv from it.
thank you all.
do like this
(not tested)
$f = file_get_contents('yourtextfile.txt');
$f = preg_replace('/\[(.*?)\]/s','',$f);
$f = str_replace(array("\n", "\r"), '', $f);
file_put_contents('temp.txt',$f);
$file = file('temp.txt');
foreach($file as $key => $line){
if($line!=null || $line!='')
{
mysqli_query($connection,"insert into table1(column1) values('$line')");
}
}
edit
$f = file_get_contents('tt.txt');
$f = preg_replace('/\[(.*?)\]/s','',$f);
$keywords = preg_split("/[ ]{15}/", $f);
print_r(array_filter($keywords));
i'm still not clear,whether you have those numbers in your file or you have just mentioned it there!!

php: count instances of words in a given string then return top 5 which match in another array

php: sort and count instances of words in a given string
In this article, I have know how to count instances of words in a given string and sort by frequency. Now I want make a further work, match the result words into anther array ($keywords), then only get the top 5 words. But I do not know how to do that, open a question. thanks.
$txt = <<<EOT
The 2013 Monaco Grand Prix (formally known as the Grand Prix de Monaco 2013) was a Formula One motor race that took place on 26 May 2013 at the Circuit de Monaco, a street circuit that runs through the principality of Monaco. The race was won by Nico Rosberg for Mercedes AMG Petronas, repeating the feat of his father Keke Rosberg in the 1983 race. The race was the sixth round of the 2013 season, and marked the seventy-second time the Monaco Grand Prix has been held. Rosberg had started the race from pole.
Background
Mercedes protest
Just before the race, Red Bull and Ferrari filed an official protest against Mercedes, having learned on the night before the race of a three-day tyre test undertaken by Pirelli at the venue of the last grand prix using Mercedes' car driven by both Hamilton and Rosberg. They claimed this violated the rule against in-season testing and gave Mercedes a competitive advantage in both the Monaco race and the next race, which would both be using the tyre that was tested (with Pirelli having been criticised following some tyre failures earlier in the season, the tests had been conducted on an improved design planned to be introduced two races after Monaco). Mercedes stated the FIA had approved the test. Pirelli cited their contract with the FIA which allows limited testing, but Red Bull and Ferrari argued this must only be with a car at least two years old. It was the second test conducted by Pirelli in the season, the first having been between race 4 and 5, but using a 2011 Ferrari car.[4]
Tyres
Tyre supplier Pirelli brought its yellow-banded soft compound tyre as the harder "prime" tyre and the red-banded super-soft compound tyre as the softer "option" tyre, just as they did the previous two years. It was the second time in the season that the super-soft compound was used at a race weekend, as was the case with the soft tyre compound.
EOT;
$words = array_count_values(str_word_count($txt, 1));
arsort($words);
var_dump($words);
$keywords = array("Monaco","Prix","2013","season","Formula","race","motor","street","Ferrari","Mercedes","Hamilton","Rosberg","Tyre");
//var_dump($words) which should match in $keywords array, then get top 5 words.
You already have $words as an associative array, indexed by the word and with the count as the value, so we use array_flip() to make your $keywords array an associative array indexed by word as well. Then we can use array_intersect_key() to return only those entries from $words that have a matching index entry in our flipped $keywords array.
This gives a resulting $matchWords array, still keyed by the word, but containing only those entries from the original $words array that match $keywords; and still sorted by frequency.
We then simply use array_slice() to extract the first 5 entries from that array.
$matchWords = array_intersect_key(
$words,
array_flip($keywords)
);
$matchWords = array_slice($matchWords, 0, 5);
var_dump($matchWords);
gives
array(5) {
'race' =>
int(11)
'Monaco' =>
int(7)
'Mercedes' =>
int(5)
'Rosberg' =>
int(4)
'season' =>
int(4)
}
Caveat: You could have problems with case-sensitivity. "Race" !== "race", so the $words = array_count_values(str_word_count($txt, 1)); line will treat these as two different words.

Categories