I need some help with an array and a foreach loop,
I have an array that is data returned from a database, basically it is a list of titles and images associated with it, it looks a little like this,
Array
(
[0] => Array
(
[contentImageId] => 28
[contentImageName] => yellow.png
[contentImageType] => .png
[contentImagePath] => /var/www/bangmarketing.bang/media/uploads/contentImages/7/yellow.png
[isHeadlineImage] => 1
[contentImageDateUploaded] => 1265388055
[contentId] => 7
[dashboardUserId] => 0
[contentTitle] => Another Blog
[contentAbstract] => <p>This is another blog and it is shit becuase this does not work</p>
[contentBody] => <p>ioasfihfududfhdufhuishdfiudshfiudhsfiuhdsiufhusdhfuids</p>
[contentOnline] => 1
[contentAllowComments] => 0
[contentDateCreated] => 1265388034
[categoryId] => 1
[categoryTitle] => blogsss
[categoryAbstract] => <p>asdsdsadasdsadfdsgdgdsgdsgssssssssssss</p>
[categorySlug] => blog
[categoryIsSpecial] => 0
[categoryOnline] => 1
[categoryDateCreated] => 1266588327
)
[1] => Array
(
[contentImageId] => 31
[contentImageName] => sophie.jpg
[contentImageType] => .jpg
[contentImagePath] => /var/www/bangmarketing.bang/media/uploads/contentImages/9/sophie.jpg
[isHeadlineImage] => 1
[contentImageDateUploaded] => 1265713423
[contentId] => 9
[dashboardUserId] => 0
[contentTitle] => Bang appoints a new Senior Designer
[contentAbstract] => <p>Bang has appointed a new Senior Designer in the wake of a number of major client wins.</p>
[contentBody] => <p>After recently signing up clients including the National Trust and Propaganda, Bang has hired Sophie Smith to join its creative team.</p>
<p>Sophie brings over twelve years of extensive design experience in Bang's core market sectors, including social housing and public sector brands.</p>
<p>Sophie has significant experience of branding and strategic design projects for a broad range of clients, including HBoS, Harvey's, TKMaxx and Places for People.</p>
<p>Warren Watts Creative Director at Bang commented; "Sophie has already proven an invaluable addition to our growing studio. In only her second week, she helped produce the creative that led to the National Trust account win".</p>
[contentOnline] => 1
[contentAllowComments] => 0
[contentDateCreated] => 1265713155
[categoryId] => 8
[categoryTitle] => News
[categoryAbstract] => <p>The world at Bang Marketing moves fast, keep up to date w
[categorySlug] => news
[categoryIsSpecial] => 0
[categoryOnline] => 1
[categoryDateCreated] => 1265283717
)
[2] => Array
(
[contentImageId] => 32
[contentImageName] => selectadna.jpg
[contentImageType] => .jpg
[contentImagePath] => /var/www/bangmarketing.bang/media/uploads/contentImages/10/selectadna.jpg
[isHeadlineImage] => 1
[contentImageDateUploaded] => 1265713937
[contentId] => 10
[dashboardUserId] => 0
[contentTitle] => Bang client experiences growth
[contentAbstract] => <p>Selectamark, the UK's leading asset protection specialist recorded its best figures for five years in 2008.</p>
[contentBody] => <p>The results were released during an extremely challenging economic climate, and just over 12 months into the organisation's relationship with Bang.</p>
<p>Bang has been working on developing Selectamark's range of product brands, which include the UK's leading asset tracking and labelling system Selectamark, and second generation forensic marking system, SelectaDNA. Despite gloomy national economic forecasts, Selectamark has enjoyed an extremely successful start to 2009 – picking up several major new clients in February, and with discussions taking place to expand operations beyond the UK and Netherlands to Germany and New Zealand.</p>
<p>Chris Garratt, Marketing Director at Bang Marketing Ltd explained "Selectamark adopted a well planned, coordinated and consistent strategy in 2008, and the results speak for themselves.</p>
<p>"Due to the success last year and the forecasts for increased levels of acquisitive crime we're hoping Selectamark's key products will enjoy similar growth in 2009".</p>
<p>Selectamark Security Systems provides DNA Forensic Marking products (SelectaDNA) and Visible Marking solutions (Selectamark and Logomark) to prevent burglaries, theft from void properties, theft of boilers, and theft of valuable metals such as lead from roofs. Selectamark have supplied these Secured By Design crime prevention products to Police, local authorities and housing associations for 25 years.</p>
<p>The Selectamark system has now marked over 25 million items, and is patented and distributed world-wide. Visit www.selectadna.co.uk for product details.</p>
<p>James Brown, Sales Director at Selectamark said "We have been absolutely delighted with the work Bang has done for us. In a short space of time, the Bang team has created a wide range of extremely fresh and professional-looking sales and marketing material for us to use, as well as devising a detailed marketing strategy which has now been implemented. We would have no hesitation in recommending Bang to other organisations."</p>
[contentOnline] => 1
[contentAllowComments] => 0
[contentDateCreated] => 1265713888
[categoryId] => 8
[categoryTitle] => News
[categoryAbstract] => <p>The world at Bang Marketing moves fast, keep up to date w
[categorySlug] => news
[categoryIsSpecial] => 0
[categoryOnline] => 1
[categoryDateCreated] => 1265283717
)
)
As you can see the contentTitle changes, everytime but sometime is returns the same content title, I am looking for a way to add a divide between the returned data, if the content Title value changes?
Is this possible? and how? I am really struggling here.
Thanks
As you loop through, you can have a temporary variable to store the last displayed title
$lastTitle='';
foreach ($array as $record)
{
if ($lastTitle != $record['contentTitle'])
echo '<hr>';
$lastTitle = $record['contentTitle');
// display content from record
}
If I understand you correctly, you want to display a divider every time the contentTitle is different from the value it had in the last iteration.
You're making a kind of gallery here, aren't you?
If so, I would go about it like this:
$lastTitle = '';
foreach($yourArray as $value)
{
if(!$lastTitle || $lastTitle != $value['contentTitle'])
{
echo '<h2>' . $value['contentTitle'] . '</h2><hr />'; // Display divider
// Do some other stuff
}
$lastTitle = $value['contentTitle'];
// Display image or whatever you want to do
}
Related
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.
I have the following PHP regex:
#<tr[\s\S]*?<a class="b1"[\s\S]*?<em[^>]*>([^<]*)[\s\S]*?stars_small_([0-9].[0-9])#
Which I am using on this site:
Gamespy
I get back this data:
[1] => Array
(
[0] => AC/DC Live: Rock Band Track Pack
[1] => Ace Combat 6: Fires of Liberation
[2] => All-Pro Football 2K8
[3] => Alone in the Dark
[4] => Armored Core 4
[5] => Army of Two
[6] => Army of Two: The 40th Day
)
[2] => Array
(
[0] => 3.5
[1] => 2.5
[2] => 3.5
[3] => 3.5
[4] => 2.5
[5] => 3.5
[6] => 3.5
)
This is what I am looking for, however I don't seem to be getting back all of the data. I should get the following Titles with scores. But for some reason I am only getting some of them.
AC/DC Live: Rock Band Track Pack
Ace Combat 6: Fires of Liberation
Afro Samurai
Alan Wake
Aliens vs. Predator
All-Pro Football 2K8
Alone in the Dark
Amped 3
Armored Core 4
Army of Two
Army of Two: The 40th Day
Assassin's Creed
Assassin's Creed II
Assassin's Creed: Brotherhood
Avatar: The Game
I have tested my regex here:
http://www.solmetra.com/scripts/regex/index.php
Using this HTML:
http://justpaste.it/20u5
Any help explaining why I am only getting back some of the results would be greatly appreciated. Thanks
Change the sub-pattern stars_small_([0-9].[0-9]) to stars_small_([0-9](?:\.[0-9])?) as some of the urls only have one digit in the SRC attribute of the IMG tag.
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
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.
After getting negative feedback from asking this question in a new question... here is my revised question. Yes it is the same project I am working on, but I was unclear that I needed to basically have a Round Robin type of scheduler.
I'm working on a Round Robin Style Hockey League Scheduler, and need some help.
The overall goal is for the end admin user to be able to punch in 3 variables and have it perform a round Robin style schedule until the WEEKS counter has been hit. Below is an example of the amount of teams and the amount of weeks games are played.
$Teams = array('team1','team2','team3','team4','team5','team6','team7','team8');
$Weeks = 16;
The goal is to have it loop 16 times, making 4 games a week, having each team playing 1 time a week. The round robin algorithm should have teams playing different teams each week until all possibles combinations have been made, but not exceeding 16 weeks. In the event that we only have 4 teams or less teams than possible combinations, we would need to have the round robin start over again until the weeks number was hit.
EDIT:
I am about 90% into what I needed this script to do... but I am stuck on one thing. I need help with merging a multi-dimensional array.
First are the Tiers. Next are the Weeks (all are week 1). Then are the Games for the team match up.
Array
(
[1] => Array
(
[1] => Array
(
[1] => Array
(
[home] => Whalers
[visitor] => Lumberjacks
)
[2] => Array
(
[home] => Team America
[visitor] => Wolfpack
)
)
)
[2] => Array
(
[1] => Array
(
[1] => Array
(
[home] => Warriors
[visitor] => Litchfield Builders
)
[2] => Array
(
[home] => Icemen
[visitor] => Nighthawks
)
)
)
[3] => Array
(
[1] => Array
(
[1] => Array
(
[home] => The Freeze
[visitor] => Devils Rejects
)
[2] => Array
(
[home] => Cobras
[visitor] => New Haven Raiders
)
[3] => Array
(
[home] => Crusaders
[visitor] => Whalers
)
[4] => Array
(
[home] => Blizzard
[visitor] => CT Redlines
)
)
)
)
I want the end result to drop the tier and merge all same weeks games together to look like the following:
Array
(
[1] => Array
(
[1] => Array
(
[home] => Whalers
[visitor] => Lumberjacks
)
[2] => Array
(
[home] => Team America
[visitor] => Wolfpack
)
[3] => Array
(
[home] => Warriors
[visitor] => Litchfield Builders
)
[4] => Array
(
[home] => Icemen
[visitor] => Nighthawks
)
[5] => Array
(
[home] => The Freeze
[visitor] => Devils Rejects
)
[6] => Array
(
[home] => Cobras
[visitor] => New Haven Raiders
)
[6] => Array
(
[home] => Crusaders
[visitor] => Whalers
)
[8] => Array
(
[home] => Blizzard
[visitor] => CT Redlines
)
)
)
Maybe something like this?
<?php
$teams = array(
'Team 1',
'Team 2',
'Team 3',
'Team 4',
'Team 5',
'Team 6',
'Team 7',
'Team 8'
);
function getMatches($teams) {
shuffle($teams);
return call_user_func_array('array_combine', array_chunk($teams, sizeof($teams) / 2));
}
for ($i = 0; $i < 14; $i += 1) {
print_r(getMatches($teams));
}
I didn't really get how you define the schedule, so if you can explain this a bit, I'll try to help.
Pop one off, randomize, pop another. There's your game. If one is left over, some random team has to be a workhorse and play two games this week:
for ($week=1; $i<=$totalWeeksPlayed; $i++)
{
$games = 0;
$temp = $teams;
while (count($temp) > 1)
{
$team = array_shift($temp);
shuffle($temp);
$opponent = array_shift($temp);
$game[$week][$games] = $team . ' vs' . $opponent;
$games++;
}
if (count($temp) == 1)
{
$workhorses = $teams;
unset($workhorses[array_search($temp[0], $teams));
shuffle($workhorses);
$team = $temp[0];
$opponent = array_shift($workhorses);
$game[$week][$games] = $team . ' vs' . $opponent;
$games++;
}
}
Question below copied from above.
Correct me if I get this wrong, but if all teams have to play on the same regular basis, is it even possible to have all teams play the same amount of matches, if there is an odd number of teams? – Yoshi May 3 '11 at 15:05
Michelle,
The number of teams you are trying to pair-up (in this case 8 teams for 16 weeks) can be a daunting task, and is just the beginning of the "scheduling process". Once the correct, balanced team pairings have been determined, it's just the beginning of putting a schedule together for distribution. Next, a list of the 4 weekly time slots includes the; day of the week, start time and location name for each time slot for the whole 16 week season. Comment: What would be most helpful for you is to get an 8 team scheduling matrix that has balanced opponent, and home & away status. It makes a big difference in the quality of a schedule. It's important to evenly distribute early and late time slots, equal home & away status, and equal team distribution with opponents. Most of the balance is accomplished by using a balanced team pair matrix.
After 35 years of teaching, coaching and scheduling sports in the Boston area, I can offer the following information. Creating league or game schedules for sports organizations seems to be a never ending task shared by many and is repeated over and over as the ages of the participants grow and those running the leagues change, the learning curve associated with creating schedules is significant for those who take over.
With that said, I am amazed at how many highly educated mathematical wizards are involved with trying to come up with the perfect solution (algorithm) that will solve one's scheduling problem. Myself and a friend (who is a mathematical/programmer genius) over a period of 3 years created software that perfectly balances all the important components when creating schedules for 4 to 22 teams. What we learned is that there is no algorithm that can handle all the possible variables that are added to the normal variables to create balanced schedules. What I am saying is there are just as many "what ifs" as there are mathematical permutations and combinations that deal with just creating a team matrix listing opponents and home & visitor status of games.
For example: Let's create a perfectly balanced schedule for an 9 team division playing 4 games a week. After nine weeks all teams have played played 8 games, all have had 1 bye, all have played two times in each of the 4 time slots, and all have been scheduled as the home team 4 times and the visitor team 4 times.
What more could anybody want? Well now comes the fun. Because the 4 time slots you chose has 2 games each Saturday, and 2 games each Sunday, the first problem pops up (after the schedules are created, published and passed out, when 2 coaches from 2 different teams call and say they work Saturdays, can you move our games to Sundays? Sure, I can do that. I'll just make the changes, re-publish and re-distribute the schedules.
After the new schedules are distributed, several days later, a different coach calls up and says, "Hey, you moved some of my games to Saturday, I work Saturdays.., move them back". The phone rings again. This time a it's a coach from another team and says they are in a tournament the 5th week of the schedule and can't play that week. Finally the last call comes in from yet another coach. He says the parents of one of his players teaches CCD classes Sunday afternoons, and half of his team is in the CCD class and wants to move all our Sunday games to Saturday. Enough!
My point is no matter what you do or how perfect a schedule is, the best solution is to find out as many of the player/coach team limitations or restrictions before you assign the playing days and time slots to any schedule. These unpredictable variables makes a mess out of a perfect schedule. People do get angry and complain when undesirable schedules are distributed. When a schedule is bad enough, some parents won't sign their youngster to play the following year. This happens when you have a young family with two or three small children, and Dad's work limits his ability to be there. When there is an early morning game, I think you can see the difficulty for Mom's when it all falls on her shoulders.
For those that are new to scheduling, stay with it. It gets better over time after you gain
a little experience dealing with the problems. If you purchase a scheduling software program to calculate team pairs, be careful. Insist on seeing a full single round robin of the schedule they create. Check for the things described above (about balance and distribution).
Bob R
Given a table of teams, say
team (
teamname
);
And a table of fixtures
fixture (
date;
);
With the relationship decomposed by 'playing'
playing (
fixture_date.
teamname
);
Then it's would simply be a matter of iterating through each date, then team and selecting a team at random who does not already have a fixture for that date, and who have not played the selected team (or not played the selected team recently).
Although a simpler solution would be to have team[n] (where n is 0....number of teams -1) play team[(n+(number of teams)) % X] for varying values of X.