determine if all values in array are equal
I have the following values in a single field from a mysql db
$rec1="4/1 @ 4p, 4/7 @ 4p, 4/8 @ 4p, 4/14 @ 4p, 4/15 @ 4p, 4/22 @ 4p, 4/28 @ 4p ";
$rec2="4/1 @ 4p, 4/7 @ 7p, 4/8 @ 4p, 4/14 @ 4p, 4/15 @ 4p, 4/22 @ 4p, 4/2开发者_Python百科8 @ 4p ";
I need to determine whether all of the time values are the same and if so return just the single time value, otherwise return the entire string.
In two records above I would want returned value to be -
$rec1=4p
(all the times were equal, don't care about the dates)
$rec2= unchanged
from original $rec2
above since at least one of the time values is different.
Give this a shot:
$rec1="4/1 @ 4p, 4/7 @ 4p, 4/8 @ 4p, 4/14 @ 4p, 4/15 @ 4p, 4/22 @ 4p, 4/28 @ 4p ";
$rec2="4/1 @ 4p, 4/7 @ 7p, 4/8 @ 4p, 4/14 @ 4p, 4/15 @ 4p, 4/22 @ 4p, 4/28 @ 4p ";
function wtf($over) {
$split = split(",",$over);
$times = array();
foreach ($split as $schedule) {
$parts = split("@",$schedule);
$times[] = trim($parts[1]);
}
$times = array_unique($times);
if (count($times) == 1) return $times[0];
return $over;
}
echo wtf($rec1);
echo "<BR>";
echo wtf($rec2);
Verified working at: http://gfosco.kodingen.com/6241557.php
Use either array_unique
or array_count_values
精彩评论