所以,我有一个数组,其中有6个变量,我需要相互检查。为了确定返回到调用函数的脚本的内容..所有字段都属于派生它们的数据库中的datetime类型。
字段:in1 out1 in2 out2 in3 out3
数组:
Array(
'in1' => '2012-04-02 10:00:00),
`out1` => '2012-04-02 14:00:00`,
`in2` => '2012-04-02 14:30:00`,
`out2` => '2012-04-02 18:00:00`,
`in3` => NULL,
`out3` => NULL
)回应:
clocked_in或clocked_out
我需要弄清楚的是,通过检查这个数组来确定用户是打卡还是打卡的最好方法。
因此,如果in1、out1和in2不为NULL,则用户将被打卡。如果in1不为NULL但out1为NULL,则用户将被注销,依此类推。有没有人知道最简单的方法,不用太多的if语句就可以做到这一点?
什么管用?
for ($i=1; $i <= 3; $i++) {
if ($entities["in$i"] != NULL) {
$ents = "clocked_in";
if ($entities["out$i"] != NULL) {
$ents = "clocked_out";
}
if ($entities["out3"] != NULL) {
$ents = "day_done";
}
}
}发布于 2012-04-03 06:00:47
你应该做的就是把他们当配对对待。您应该一次循环两个数组,检查是否设置了时钟输入,如果设置了时钟输出,则设置了时钟输出。在此过程中更新一个变量以确保。
$clocked = '';
for($i=0; $i <= sizeOf($arr); $i+2) // $arr is your array of clock in and outs
{
if(arr[$i] != NULL)
{
// Our Clock In is Not Null and Our Clock Out is.. meaning we're clocked in.
if(arr[$i+1] == NULL) // check clock out
{
$clocked = "clocked in";
break; //Break out so we don't check the other pairs because we know we're clocked in.
}
else //Clock Out Exists, so far we're clocked out.
{
$clocked = "clocked Out"; // We can't break here. There might be more clock in/out pairs left to check.
}//end clock out check
}// end clock in check
}// end for loop
echo $clocked;这有点难,因为我很快就写好了。如果有任何语法错误,我很抱歉,但这是我使用的基本概念。
发布于 2012-04-03 12:00:33
这里有一种更时髦的方式,没有嵌套:
# the fields as array $a: in1 out1 in2 out2 in3 out3
function is_clocked_in( $a ) {
$c = (count(array_intersect( $a, array(null) ))) % 2;
return( $c ? true : false );
}这背后的理论是,array_intersect会返回空字段的数量;之后,您会发现这个数字是偶数或奇数,这意味着进入/退出状态。示例使用"t“表示一个非空值,但它应该是一个字符串时间戳。
var_dump( is_clocked_in( array( null, null, null, null, null, null ) ) ); // f
var_dump( is_clocked_in( array( "t", null, null, null, null, null ) ) ); // T
var_dump( is_clocked_in( array( "t", "t", null, null, null, null ) ) ); // f
var_dump( is_clocked_in( array( "t", "t", "t", null, null, null ) ) ); // T
var_dump( is_clocked_in( array( "t", "t", "t", "t", null, null ) ) ); // f
var_dump( is_clocked_in( array( "t", "t", "t", "t", "t", null ) ) ); // T
var_dump( is_clocked_in( array( "t", "t", "t", "t", "t", "t") ) ); // fhttps://stackoverflow.com/questions/9983994
复制相似问题