数据库设计按位存储
sanlanlan 2018-6-21 标签: mysql 浏览:1762 评论:0
比如某个type 字段,存储可以选择,原创,搞笑,人物,好看等来存储,相当于页面的选择是选项多选。
这时候,可以使用按位来存储。
class Bit{
//begin
public static function setBit($index, $bitValue){
$bitValue = $bitValue | (1 << $index);
return $bitValue;
}
public static function setBits(array $indexList, $bitValue){
$mask = 0;
foreach ($indexList as $index) {
$mask = $mask | (1 << $index);
}
}
$bitValue = self::setBitsByMask($mask, $bitValue);
return $bitValue;
}
public static function setBitsByMask($mask, $bitValue){
$bitValue = $bitValue | $mask;
return $bitValue;
}
public static function unsetBit($index, $bitValue){
$bitValue = $bitValue & ~(1 << $index);
return $bitValue;
}
public static function unsetBits(array $indexList, $bitValue){
$mask = 0;
foreach ($indexList as $index) {
$mask = $mask | (1 << $index);
}
$bitValue = self::unsetBitsByMask($mask, $bitValue);
return $bitValue;
}
public static function unsetBitsByMask($mask, $bitValue) {
$bitValue = $bitValue & ~$mask;
return $bitValue;
}
public static function getArray ($bitValue, $keyArr = array(), $keyName = array()) {
$output = [];
$bitArr = array_reverse(str_split(base_convert($bitValue, 10, 2)));
if(!empty($keyArr)) {
$tmp = [];
foreach ($keyArr as $key) {
$tmp[$key] = isset($bitArr[$key]) ? (int) $bitArr[$key] : 0;
}
$bitArr = $tmp;
}
if(empty($keyName)) return $bitArr;
foreach ($bitArr as $k=>$val) {
if($val && isset($keyName[$k])) {
$output[] = $keyName[$k];
}
}
return $output;
}
public static function isBitSet($index, $bitValue){
return (bool) ($bitValue & (1 << $index));
}
}
class UseBit{
const BIT_0 = 0;
const BIT_1 = 1;
const BIT_2 = 2;
const BIT_3 = 3;
const BIT_4 = 4;
//你要操作的数组
public static $BitArr = [
self::BIT_0 =>'a',
self::BIT_1 =>'b',
self::BIT_2 =>'c',
self::BIT_3 =>'d',
self::BIT_4 =>'e'
];
public static function testSet(){
$post = [0,2,3];
$mask = 0;
$keys = array_keys(self::$BitArr);
foreach ($post as $key) {
if(in_array($key, $keys)){
$mask = Bit::setBit($key, $mask);
}
}
echo $mask;
$a = [2,3,4];
$b = [
'a'=>8,
'b'=>7,
'c'=>6,
];
$a = array_reverse($a);
$b = array_reverse($b);
var_dump($a);
var_dump($b);
}
}
UseBit::testSet()."set\n";
发表评论: