我有一个带有工作日名称的复选框列表,这些值为[1,2,4,8,16,32,64]
<label class="m-checkbox">
<input type="checkbox" name="selected_days[]" value="1" id="check_sun"/>Sunday<span></span>
</label>
<label class="m-checkbox">
<input type="checkbox" name="selected_days[]" value="2" id="check_mon"/>Monday<span></span>
</label>
<label class="m-checkbox">
<input type="checkbox" name="selected_days[]" value="4" id="check_tue"/>Tuesday<span></span>
</label>
<label class="m-checkbox">
<input type="checkbox" name="selected_days[]" value="8" id="check_wed"/>Wednesday<span></span>
</label>
<label class="m-checkbox">
<input type="checkbox" name="selected_days[]" value="16" id="check_thu"/>Thursday<span></span>
</label>
<label class="m-checkbox">
<input type="checkbox" name="selected_days[]" value="32" id="check_fri"/> Friday<span></span>
</label>
<label class="m-checkbox">
<input type="checkbox" name="selected_days[]" value="64" id="check_sat"/> Saturday<span></span>
</label>
在保存它们的同时,我对选定的复选框进行了总计以存储在数据库中
<?php array_sum($post_data["selected_days"]);?>
所以问题在于,我需要正确地选择一些复选框。我找不到如何显示总和的选定复选框
例如:选择周一,周二和周六,因此DB值将为70(2 + 4 + 64) 当我从DB那里得到70岁时,我怎么知道这些仅是Mon,Tue和Sat
请帮我做
答案 0 :(得分:2)
您可以使用按位运算符
DB Sum Column & Input Day = Input Day
70 & 4 = 4
70 & 2 = 2
70 & 64 = 64
其他日期该值为0。
更新
$daysArr = [1=>'Sunday', 2=>'Monday', 4=>'Tuesday', 8=>'Wednesday', 16 => 'Thursday', 32=>'Friday', 64=>'Saturday'];
$selectedArr = [];
$dbData = 70; //Your db result here
foreach($daysArr as $selDay => $selDayName)
{
if($dbData & $selDay){
$selectedArr[] = $selDay;
}
}
print_r($selectedArr);
用于检查动态值的PHP代码。
答案 1 :(得分:1)
$sum = 29;
$days = array("Sun","Mon","Tue","Wed","Thur","Fri","Sat");
$selected = str_split(decbin($sum));
$count = count($selected);
echo "Checked days are ";
for($i=0;$i<=$count-1;$i++){
if($selected[$i]==1){
echo $days[$i] ." ";
}
}