2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

ビットフラグでシフトを管理してみる

Last updated at Posted at 2015-06-08

シフト時間なんかを時間(コマ)のチェックボタンで入力および管理をしてみます。
入力フォームには、0時から23時までのチェックボックスが並び、チェックのオン・オフでシフト時間を指定するとします。

form.php
<form method="post" action="insert.php">
<?php for($h=0; $h<24; $h++){ ?>
  <label>
    <input type="checkbox" name="hours[]" value="<?php echo $h; ?>">
    <?php echo $h; ?>時
  </label>
<?php } ?>
  <button type="submit" name="mode" value="submit">送信</button>
</form>

チェックされた時間を1、チェックされなかった時間を0として文字列にします。
例えば、
9時から18時のシフトなら 000000000111111111100000
9時から11時、15時から18時なら 000000000111000111100000
といった風にします。
その文字列を「2進数→10進数」に変換してDBに登録します。

insert.php
// フォーム処理
if(isset($_POST['mode']) && $_POST['mode'] == 'submit'){
  
  $loginhours = $_POST['hours'];
  $loginbits = '';
  
  for($h = 0; $h < 24; $h++){
    // チェックされていたら1 なかったら0
    $loginbits .= (in_array($h, $loginhours)) ? '1' : '0';
  }
  
  // 2進数から10進数に変換
  $loginbits10 = bindec($loginbits);
  
  // 10進数に変換された数値をDBに登録
  $db->insert('shifttime', $loginbits10, "integer");
}

表示する時は、10進数から2進数に戻し、桁数を揃えて、配列に変換して利用します。

view.php
<?php
// ログイン可能時間
// DBから shifttime を取得
$shifttimes = (string) $db->shifttime;

$shiftTimeArr = array();

// shifttime を10進数から2進数に変換
$shiftTimeStr = (string) decbin($shifttimes);

// 桁を0で埋める
// e.g. "111111111100000" → "000000000111111111100000"
$shiftTimeStr = sprintf("%024s", $logintimeStr);
// 文字列を配列に変換
$shiftTimeArr = str_split($logintimeStr);

?>
<table>
  <tr>
  <?php foreach($shiftTimeArr as $s){ ?>
    <td><?php echo ($s == 1) ? "●" : "&nbsp;"; ?></td>
  <?php } ?>
  </tr>
</table>
<p>シフトに入っている時間は●で表示</p>

今回、シフト時間を例にしてみましたが、いろいろと応用が効きそうです。
時間(コマ)を30分単位にしたい場合は、桁数を2倍にして処理すればよいのですが、既存のデータもすべて桁を合わせる必要があるので、桁を変更する必要がある場合は注意が必要です。

2
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?