首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >相互检查数组,以确定响应

相互检查数组,以确定响应
EN

Stack Overflow用户
提问于 2012-04-03 05:19:25
回答 2查看 172关注 0票数 0

所以,我有一个数组,其中有6个变量,我需要相互检查。为了确定返回到调用函数的脚本的内容..所有字段都属于派生它们的数据库中的datetime类型。

字段:in1 out1 in2 out2 in3 out3

数组:

代码语言:javascript
运行
复制
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_inclocked_out

我需要弄清楚的是,通过检查这个数组来确定用户是打卡还是打卡的最好方法。

因此,如果in1out1in2不为NULL,则用户将被打卡。如果in1不为NULL但out1为NULL,则用户将被注销,依此类推。有没有人知道最简单的方法,不用太多的if语句就可以做到这一点?

什么管用?

代码语言:javascript
运行
复制
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";
        }
    }
}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-04-03 06:00:47

你应该做的就是把他们当配对对待。您应该一次循环两个数组,检查是否设置了时钟输入,如果设置了时钟输出,则设置了时钟输出。在此过程中更新一个变量以确保。

代码语言:javascript
运行
复制
$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;

这有点难,因为我很快就写好了。如果有任何语法错误,我很抱歉,但这是我使用的基本概念。

票数 1
EN

Stack Overflow用户

发布于 2012-04-03 12:00:33

这里有一种更时髦的方式,没有嵌套:

代码语言:javascript
运行
复制
# 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“表示一个非空值,但它应该是一个字符串时间戳。

代码语言:javascript
运行
复制
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") ) );          // f
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/9983994

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档