PHP separate string by specific array of words - php

I've array in php with following values
Array
(
[0] => Clarithromycin 250mg/5ml oral susptake TWO 5ml spoonsful TWICE each day DISCARD REMAINING AFTER TEN DAYSSHAKE THE BOTTLE WELL BEFORE USING.SPACE THE DOSES EVENLY. KEEP TAKING UNTIL THE COURSE IS FINISHED, UNLESS YOU ARE TOLD TO STOP.
[1] => Lactulose 3.1-3.7g/5ml oral solntake ONE to FOUR 5ml spoonsful TWICE each day when required (PRN : to be taken when necessary)
[2] => Mirtazapine orodisp 30mg tabsOne To Be Taken At NightALLOW THE TABLETS TO DISSOLVE ON YOUR TONGUE, THEN SWALLOW WITH THE SALIVA. TAKE AFTER FOOD.WARNING: THIS MEDICINE MAY MAKE YOU FEEL SLEEPY. IF THIS HAPPENS, DO NOT DRIVE OR USE TOOLS OR MACHINES. DO NOT DRINK ALCOHOL.
[3] => Senna 7.5mg/5ml oral soln SFTwo 5ml Spoonfuls To Be Taken At NightSHAKE THE BOTTLE WELL BEFORE USING.THIS MEDICINE MAY COLOUR YOUR URINE. THIS IS HARMLESS.
[4] => SUDOCREM ANTISEPTIC HEALING CREAMas directedFOR EXTERNAL USE ONLY. (MD mean As directed)
[5] => CIRCADIN MR 2MG TABSOne To Be Taken At NightSWALLOW WHOLE. DO NOT CHEW OR CRUSH.TAKE WITH OR JUST AFTER FOOD, OR A MEAL.WARNING: THIS MEDICINE MAY MAKE YOU FEEL SLEEPY. IF THIS HAPPENS, DO NOT DRIVE OR USE TOOLS OR MACHINES. DO NOT DRINK ALCOHOL.
[6] => Memantine 10mg tabsOne To Be Taken Each Day
[7] => Omeprazole gr 10mg capsOne To Be Taken Each DaySWALLOW WHOLE.DO NOT CHEW OR CRUSH.
[8] => Senna 7.5mg tabsTwo To Be Taken At NightTHIS MEDICINE MAY COLOUR YOUR URINE. THIS IS HARMLESS.
)
I wanna separate medicine and description by specific words. e.g (take two,one to be taken,one to,to be taken etc.....)
array
(
[0] => Array
(
[medicine] => Clarithromycin 250mg/5ml oral susp
[description] => take TWO 5ml spoonsful TWICE each day DISCARD REMAINING AFTER TEN DAYSSHAKE THE BOTTLE WELL BEFORE USING.SPACE THE DOSES EVENLY. KEEP TAKING UNTIL THE COURSE IS FINISHED, UNLESS YOU ARE TOLD TO STOP.
)
[1] => Array
(
[medicine] => Lactulose 3.1-3.7g/5ml oral soln
[description] =>take ONE to FOUR 5ml spoonsful TWICE each day when required (PRN : to be taken when necessary)
)
[2] => Array
(
[medicine] => Mirtazapine orodisp 30mg tabs
[description] => One To Be Taken At NightALLOW THE TABLETS TO DISSOLVE ON YOUR TONGUE, THEN SWALLOW WITH THE SALIVA. TAKE AFTER FOOD.WARNING: THIS MEDICINE MAY MAKE YOU FEEL SLEEPY. IF THIS HAPPENS, DO NOT DRIVE OR USE TOOLS OR MACHINES. DO NOT DRINK ALCOHOL.
)
.
.
.
.
)

try this:
foreach ($array as $key => $value) {
$explode = explode('separate', $value);
$array[$key] = array(
'medicine' => $explode[0],
'description' => $explode[1]
);
}
just edit 'separate' by the word you want to seperate your text with

//Main array
//Create array of words that you have to separate from
$arrOfsplittedData = [];
$intCount = 0;
foreach($arrOfMedicineAndDesc as $medicineAndDesc){
$lowerCaseMedicineAndDesc = strtolower($medicineAndDesc);
$splitMedicineAndDesc = multiexplode(array("oral", "tabsone", "cream", "capsone", "tabstwo"), $lowerCaseMedicineAndDesc);
if($splitMedicineAndDesc){
$arrOfsplittedData[$intCount]["medicine"] = $splitMedicineAndDesc[0];
$arrOfsplittedData[$intCount]["description"] = $splitMedicineAndDesc[1];
}
$intCount++;
}
function multiexplode ($delimiters,$string) {
$ready = str_replace($delimiters, $delimiters[0], $string);
$launch = explode($delimiters[0], $ready);
return $launch;
}
echo "<pre>";
print_r($arrOfsplittedData);die;

You can be crafty with regex to do this:
<?php
$array = array(
"Clarithromycin 250mg/5ml oral susptake TWO 5ml spoonsful TWICE each day DISCARD REMAINING AFTER TEN DAYSSHAKE THE BOTTLE WELL BEFORE USING.SPACE THE DOSES EVENLY. KEEP TAKING UNTIL THE COURSE IS FINISHED, UNLESS YOU ARE TOLD TO STOP.",
"Lactulose 3.1-3.7g/5ml oral solntake ONE to FOUR 5ml spoonsful TWICE each day when required (PRN : to be taken when necessary)",
"Mirtazapine orodisp 30mg tabsOne To Be Taken At NightALLOW THE TABLETS TO DISSOLVE ON YOUR TONGUE, THEN SWALLOW WITH THE SALIVA. TAKE AFTER FOOD.WARNING: THIS MEDICINE MAY MAKE YOU FEEL SLEEPY. IF THIS HAPPENS, DO NOT DRIVE OR USE TOOLS OR MACHINES. DO NOT DRINK ALCOHOL.",
"Senna 7.5mg/5ml oral soln SFTwo 5ml Spoonfuls To Be Taken At NightSHAKE THE BOTTLE WELL BEFORE USING.THIS MEDICINE MAY COLOUR YOUR URINE. THIS IS HARMLESS.",
"SUDOCREM ANTISEPTIC HEALING CREAMas directedFOR EXTERNAL USE ONLY. (MD mean As directed)",
"CIRCADIN MR 2MG TABSOne To Be Taken At NightSWALLOW WHOLE. DO NOT CHEW OR CRUSH.TAKE WITH OR JUST AFTER FOOD, OR A MEAL.WARNING: THIS MEDICINE MAY MAKE YOU FEEL SLEEPY. IF THIS HAPPENS, DO NOT DRIVE OR USE TOOLS OR MACHINES. DO NOT DRINK ALCOHOL.",
"Memantine 10mg tabsOne To Be Taken Each Day",
"Omeprazole gr 10mg capsOne To Be Taken Each DaySWALLOW WHOLE.DO NOT CHEW OR CRUSH.",
"Senna 7.5mg tabsTwo To Be Taken At NightTHIS MEDICINE MAY COLOUR YOUR URINE. THIS IS HARMLESS."
);
$splitWords = [
"take \w+?\b",
"to be taken"
]; //Regex of what you want to split on
$regex = "/(".implode("|",$splitWords).")/";
$replaced = preg_replace($regex, "\n$1", $array); //Replace what you found with a newline + what you found
print_r(array_map(function ($v) {
$array = explode("\n",$v);
return [
"medicine" => $array[0],
"description" => isset($array[1])?$array[1]:null
]; //If you're array is bigger than 2 elements you may need to loop here.
},$replaced)); //Split sentences on the newlines.
Here's an example:
http://sandbox.onlinephpfunctions.com/code/b2e2ceef17152e9a888a7b68fab3acb2e9f10fe3

Related

Find and Replace Multi-Row Phrases/text Within PHP Arrays without damaging the array

Lets say I have an array:
$myarray = (
[0] => 'Johnny likes to go to school',
[1] => 'but he only likes to go on Saturday',
[2] => 'because Saturdays are the best days',
[3] => 'unless you of course include Sundays',
[4] => 'which are also pretty good days too.',
[5] => 'Sometimes Johnny likes picking Strawberrys',
[6] => 'with his mother in the fields',
[7] => 'but sometimes he likes picking blueberries'
);
Keeping the structure of this array intact, I want to be able to replace phrases within it, even if they spill over to the next or previous string. Also I don't want punctuation or case to impact it.
Examples:
String to Find:
"Sundays which are also pretty good"
Replace with:
"Mondays which are also pretty great"
After replace:
$myarray = (
[0] => 'Johnny likes to go to school',
[1] => 'but he only likes to go on Saturday',
[2] => 'because Saturdays are the best days',
[3] => 'unless you of course include Mondays',
[4] => 'which are also pretty great days too.',
[5] => 'Sometimes Johnny likes picking Strawberrys',
[6] => 'with his mother in the fields',
[7] => 'but sometimes he likes picking blueberries'
);
Curious if there is an ideal way of doing this. My original thought was, I would turn the array into a string, strip out punctuation and spaces, count the characters and replace the phrase based on the character count. But, it is getting rather complex, but it is a complex problem
This is a job for regular expressions.
The method I used was to implode the array with some glue (i.e. '&'). Then I generated a regular expression by inserting a zero-or-one check for '&' in between each character in the find string.
I used the regular expression to replace occurrences of the string we were looking for with the replacement string. Then I exploded the string back into an array using the same delimiter as above ('&')
$myarray = [
0 => 'Johnny likes to go to school',
1 => 'but he only likes to go on Saturday',
2 => 'because Saturdays are the best days',
3 => 'unless you of course include Mondays',
4 => 'which are also pretty great days too.',
5 => 'Sometimes Johnny likes picking Strawberrys',
6 => 'with his mother in the fields',
7 => 'but sometimes he likes picking blueberries'
];
// preg_quote this because we're looking for the string, not for a pattern it might contain
$findstring = preg_quote("Sundays which are also pretty good");
// htmlentities this in case it contains a string of characters which happen to be an html entity
$replacestring = htmlentities("Mondays which are also pretty great");
// Combine array into one string
// We use htmlentitles to escape the ampersand, so we can use it as a sentence delimeter
$mystring = implode("&", array_map('htmlentities', $myarray));
// Turns $findString into:
// S\&?u\&?n\&?d\&?a\&?y\&?s\&? \&?w\&?h\&?i\&?c\&?h\&? \&?a\&?r\&?e\&?
// \&?a\&?l\&?s\&?o\&? \&?p\&?r\&?e\&?t\&?t\&?y\&? \&?g\&?o\&?o\&?d
$regexstring = implode("\&?", str_split($findstring));
// Johnny likes to go to school&but he only likes to go on Saturday&because Saturdays are the
// best days&unless you of course include Mondays&which are also pretty great days
// too.&Sometimes Johnny likes picking Strawberrys&with his mother in the fields&but sometimes
// he likes picking blueberries
$finalstring = preg_replace("/$regexstring/", $replacestring, $mystring);
// Break string back up into array, and return any html entities which might have existed
// at the beginning.
$replacedarray = array_map('html_entity_decode', explode("&", $finalstring));
var_dump($replacedarray);

php's str_getcsv breaking on tab separated list with no enclosure and individual double quotes

I'm using str_getcsv to parse tab separated values being returned from a nosql query however I'm running into a problem and the only solution I've found is illogical.
Here's some sample code to demonstrate (FYI, it seems the tabs aren't being preserved when showing here)...
$data = '0 16 Gruesome Public Executions In North Korea - 80 Killed http://www.youtube.com/watch?v=Dtx30AQpcjw&feature=youtube_gdata "North Korea staged gruesome public executions of 80 people this month, some for offenses as minor as watching South Korean entertainment videos or being fou... 1384357511 http://gdata.youtube.com/feeds/api/videos/Dtx30AQpcjw 0 The Young Turks 1 2013-11-13 12:53:31 9ab8f5607183ed258f4f98bb80f947b4 35afc4001e1a50fb463dac32de1d19e7';
$data = str_getcsv($data,"\t",NULL);
echo '<pre>'.print_r($data,TRUE).'</pre>';
Pay particular attention to the fact that one column (beginning with "North Korea...." actually starts with a double quote " but doesn't finish with one. This is why I supply NULL as the third parameter (enclosure) to override the defaut " enclosure value.
Here is the result:
Array
(
[0] => 0
[1] => 16
[2] => Gruesome Public Executions In North Korea - 80 Killed
[3] => http://www.youtube.com/watch?v=Dtx30AQpcjw&feature=youtube_gdata
[4] =>
[5] => North Korea staged gruesome public executions of 80 people this month, some for offenses as minor as watching South Korean entertainment videos or being fou... 1384357511 http://gdata.youtube.com/feeds/api/videos/Dtx30AQpcjw 0 The Young Turks 1 2013-11-13 12:53:31 9ab8f5607183ed258f4f98bb80f947b4 35afc4001e1a50fb463dac32de1d19e7
)
As you can see the quote is breaking the function. Logically I thought I would be able to use NULL or and empty string'' as the third parameter for str_getcsv (enclosure) but neither worked?!?!
The only thing I could use to get str_getcsv to work properly was a space char ' '. That doesn't make any sense to me becuase none of the columns have whitespace starting and/or ending them.
$data = '0 16 Gruesome Public Executions In North Korea - 80 Killed http://www.youtube.com/watch?v=Dtx30AQpcjw&feature=youtube_gdata "North Korea staged gruesome public executions of 80 people this month, some for offenses as minor as watching South Korean entertainment videos or being fou... 1384357511 http://gdata.youtube.com/feeds/api/videos/Dtx30AQpcjw 0 The Young Turks 1 2013-11-13 12:53:31 9ab8f5607183ed258f4f98bb80f947b4 35afc4001e1a50fb463dac32de1d19e7';
$data = str_getcsv($data,"\t",' ');
echo '<pre>'.print_r($data,TRUE).'</pre>';
Now the result is:
Array
(
[0] => 0
[1] => 16
[2] => Gruesome Public Executions In North Korea - 80 Killed
[3] => http://www.youtube.com/watch?v=Dtx30AQpcjw&feature=youtube_gdata
[4] =>
[5] => "North Korea staged gruesome public executions of 80 people this month, some for offenses as minor as watching South Korean entertainment videos or being fou...
[6] => 1384357511
[7] => http://gdata.youtube.com/feeds/api/videos/Dtx30AQpcjw
[8] => 0
[9] => The Young Turks
[10] =>
[11] =>
[12] =>
[13] =>
[14] => 1
[15] => 2013-11-13 12:53:31
[16] => 9ab8f5607183ed258f4f98bb80f947b4
[17] => 35afc4001e1a50fb463dac32de1d19e7
)
So my question is, why does it work with a space as the enclosure, but not NULL or and empty string? Also are there repercussions to this?
UPDATE 1: It seems this reduced the number of errors I was receiving in our logs but it didn't eliminate them, so I'm guessing that the I used as the enclosure has caused unintended side effects, albeit less troubling than the previous problem. But my question remains the same, why can't I use NULL, or an empty space as the enclosure, and secondly, is there a better way of dealing with / doing this?
Just to give a starting point ...
You might wanna consider working with the string itself, instead of using a function like str_getcsv in your case.
But be aware that there are at least some pitfalls, if you choose this route (might be your only option though):
Handling of escaped characters
Line breaks within the data (not meant as delimiters)
If you know that you don't have any other TABS in your string other than those ending the fields, and you don't have any linebreaks other than those delimiting a row, you might be fine with this:
$data = explode("\n", $the_whole_csv_string_block);
foreach ($data as $line)
{
$arr = explode("\t", $line);
// $arr[0] will have every first field of every row, $arr[1] the 2nd, ...
// Usually this is what I want when working with a csv file
// But if you rather want a multidimensional array, you can simply add
// $arr to a different array and after this loop you are good to go.
}
Otherwise this is just a starting point for you, to begin and tweak it to your individual situation, hope it helps.
Simply use chr(0) as enclosure and escape:
$data = str_getcsv($data, "\t", chr(0), chr(0));

split text by words and punctuation marks

I have this text:
A man’s jacket is of green color. He – the biggest star in modern history – rides bikes very fast (230 km per hour). How is it possible?! What kind of bike is he using? The semi-automatic gear of his bike, which is quite expensive, significantly helps to reach that speed. Some (or maybe many) claim that he is the fastest in the world! “I saw him ride the bike!” Mr. John Deer speaks. “The speed he sets is 133.78 kilometers per hour,” which sounds incredible; sounds deceiving.
I want to have the following resulting array:
words[1] = "A"
words[2] = "man's"
words[3] = "jacket"
...
words[n+1] = "color"
words[n+2] = "."
words[n+3] = "He"
words[n+4] = "-"
words[n+5] = "the"
...
This array should include all words and punctuation marks separately. Can that be performed using regexp? Can anyone help to compose it?
Thanks!
EDIT: based on request to show my work.
I'm processing the text using the following function, but I want to do the same in regex:
$text = explode(' ', $this->rawText);
$marks = Array('.', ',', ' ?', '!', ':', ';', '-', '--', '...');
for ($i = 0, $j = 0; $i < sizeof($text); $i++, $j++) {
$skip = false;
//check if the word contains punctuation mark
foreach ($marks as $value) {
$markPosition = strpos($text[$i], $value);
//if contains separate punctation mark from the word
if ($markPosition !== FALSE) {
//check position of punctation mark - if it's 0 then probably it's punctuation mark by itself like for example dash
if ($markPosition === 0) {
//add separate mark to array
$words[$j] = new Word($j, $text[$i], 2, $this->phpMorphy);
} else {
$words[$j] = new Word($j, substr($text[$i], 0, strlen($text[$i]) - 1), 0, $this->phpMorphy);
//add separate mark to array
$punctMark = substr($text[$i], -1);
$j += 1;
$words[$j] = new Word($j, $punctMark, 1, $this->phpMorphy);
}
$skip = true;
break;
}
}
if (!$skip) {
$words[$j] = new Word($j, $text[$i], 0, $this->phpMorphy);
}
}
The following will split on your specific text.
$words = preg_split('/(?<=\s)|(?<=\w)(?=[.,:;!?()-])|(?<=[.,!()?\x{201C}])(?=[^ ])/u', $text);
See working demo
Try making use of preg_split. Pass your punctuations(of your choice) inside the square brackets [ and ]
<?php
$str="A man’s jacket is of green color. He – the biggest star in modern history – rides bikes very fast (230 km per hour). How is it possible?! What kind of bike is he using? The semi-automatic gear of his bike, which is quite expensive, significantly helps to reach that speed. Some (or maybe many) claim that he is the fastest in the world! “I saw him ride the bike!” Mr. John Deer speaks. “The speed he sets is 133.78 kilometers per hour,” which sounds incredible; sounds deceiving.";
$keywords=preg_split("/[-,. ]/", $str);
print_r($keywords);
OUTPUT:
Array (
[0] => A
[1] => man’s
[2] => jacket
[3] => is
[4] => of
[5] => green
[6] => color
[7] =>
[8] => He
[9] => –
[10] => the
[11] => biggest
[12] => star
[13] => in
[14] => modern
[15] => history
[16] => –
Message truncated to prevent abuse of resources ... Shankar ;)

PHP Random Team Schedule Generator - Round Robin Scheduler

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.

php json_encode returning null

Array
(
[sEcho] => 1
[iTotalRecords] => 7521
[iTotalDisplayRecords] => 1
[aaData] => Array
(
[0] => Array
(
[0] => Nordic Capital Buys SiC Processing
[1] => 2010-06-21/nordic-capital-buys-sic-processing
[2] => PEHub Media
[3] => Business
[4] => completed
[5] => Nordic Capital has acquired a 70% stake in SiC Processing AG, a German industrial recycling company, from Frog Capital. No sale price was disclosed. SiC Processing’s founding family retains a 25% holding, while former lead investor Zouk Ventures retains a 5% stake.
[6] => Admin, China, Frog Capital, Germany, Italy, Iyad Omari, Manufacturing, Norway, PEHub Media, Photovoltaic Wafer Manufacturing, Renewable Energy, Semiconductor, United States
)
)
)
echo json_encode($myArr);
{"sEcho":"1","iTotalRecords":7521,"iTotalDisplayRecords":"1","aaData":[["
Nordic Capital Buys SiC Processing</a></div>","
2010-06-21/nordic-capital-buys-sic-processing</div>","PEHub Media","Business","completed",null,"
Admin, China, Frog Capital, Germany, Italy, Iyad Omari, Manufacturing, Norway, PEHub Media, Photovoltaic Wafer Manufacturing, Renewable Energy, Semiconductor, United States]]}
Note the null in the middle of the string after completed
Why is this, what escape/manipulation do I need to perform in order to encode this?
I have tried, addslashes
From the manual:
Note that if you try to encode an
array containing non-utf values,
you'll get null values in the
resulting JSON string. You can
batch-encode all the elements of an
array with the array_map function:
$encodedArray = array_map(utf8_encode, $myArr);
echo json_encode($encodedArray);
Actually it doesn't return null, http://codepad.org/A34KdUf5.
Maybe your PHP version doesn't support json_encode().
Works for me on 5.2.13. Ensure you're using at least PHP 5.2.0 and that PHP wasn't compiled with --disable-json. You may also want to check that error reporting (and/or logging) is enabled.
The simpler way is $store_name = utf8_encode(name_of_varaible) but please make sure that your character set is ISO-8859-1.

Categories