我有来自数据库的数组和数据,需要比较它们。
$mydays = array(
'Monday' => array('10:00','11:00','12:00','15:00','16:00','17:00','18:00'),
'Tuesday' => array('10:00','11:00','12:00','15:00','16:00','17:00','18:00'),
'Wednesday' => array('9:00','10:00','11:00','12:00','14:00','15:00','16:00','17:00','18:00'),
'Thursday' => array('9:00','10:00','11:00','12:00','14:00','15:00','16:00','17:00','18:00'),
'Friday' => array('9:00','10:00','11:00','12:00','14:00','15:00','16:00','17:00','18:00'),
'Saturday' => array('9:00','10:00','11:00','12:00')
);
$myhours = array(
"2017-02-27" => array("17:00"),
"2017-03-01" => array("16:00","17:00","18:00"),
"2017-03-03" => array("17:00"),
"2017-03-08" => array("17:00","18:00"),
"2017-03-10" => array("17:00","18:00")
);
从数据库中,我检索一些数据,例如:
$thisday = Monday
$thisdate = yyyy-mm-dd
$thishour = H:i
$myday = $mydays[$thisday];
foreach ($myday as $hour) { /* loop through hours for this specific day */
// I need to find out if there is a date/hour from "$myhours" that matches my data
// ie: I have database:Monday -> I loop through the hours from $mydays:Monday
// I then have : 10:00,11:00,12:00,15:00,16:00,17:00,18:00
// from there, I need to know if, in "$myhours", I have the same hour for "$thisdate"
}
我几乎阅读了这里的所有帖子,发现并尝试使用:
function in_multiarray($elem, $array, $field)
{
$top = sizeof($array) - 1;
$bottom = 0;
while($bottom <= $top)
{
if($array[$bottom][$field] == $elem) {
return true;
} else {
if(is_array($array[$bottom][$field])) {
if(in_multiarray_d($elem, ($array[$bottom][$field]))) {
return true; } else { return false; }
} else { return false; }
$bottom++;
}
}
return false;
}
if( !in_multiarray("$thisdate", $myhours, "$hour") ) { echo"good"; } else { echo"not good"; }
我的问题:我不是每次都得到一个结果(即使是一天/小时匹配),当我这样做时,不是每个小时,我都会错过几天/几小时......我以为我可能需要重置阵列,但没有更好的结果。
问:我的方法是解决问题的正确方法吗?如果是的话,我做错了什么?如果没有,你最好的建议是什么,或者我该怎么办?答案 0 :(得分:1)
使用in_array
函数的简单解决方案:
...
$thisday = 'Monday';
$thisdate = "2017-02-27";
$thishour = '11:00';
// check if we have a valid weekday name and date/time value
if (isset($mydays[$thisday]) && isset($myhours[$thisdate])
&& in_array($thishour, $mydays[$thisday])) {
echo 'good';
} else {
echo "not good";
}