1ビット1アイテムって思うと、最大で63個まで持ってるか分かるようになる的な。
なんで63個かっていうと64個だとMySQLにしまえない可能性があるみたい。
(使ってるVerが古いってのもあるし、そもそも勘違いかもだけどー。)
とりあえず、PHPで書いたさんぷる。
さんぷるクリプト
- // 色情報
- $items=array('red'=>1, 'blue'=>2, 'green'=>3, 'white'=>4, 'black'=>5);
- // 人情報
- $peoples = array('LILY'=>0, 'LOGAN'=>0, 'OLIVIA'=>0);
- /*
- * 選択情報を作る
- */
- $peoples['LILY'] =
- (1 << $items['red'])
- | (1 << $items['green'])
- | (1 << $items['black']) ; // red, green, black を選ぶ
- printf("name:% 7s int:% 4d bit:%08b\n",
- 'LILY', $peoples['LILY'], $peoples['LILY']);
- $peoples['LOGAN'] =
- (1 << $items['blue'])
- | (1 << $items['green'])
- | (1 << $items['black']) ; // blue, green, black を選ぶ
- printf("name:% 7s int:% 4d bit:%08b\n",
- 'LOGAN', $peoples['LOGAN'], $peoples['LOGAN']);
- $peoples['OLIVIA'] =
- (1 << $items['red'])
- | (1 << $items['white'])
- | (1 << $items['black']) ; // red, white, black を選ぶ
- printf("name:% 7s int:% 4d bit:%08b\n",
- 'OLIVIA', $peoples['OLIVIA'], $peoples['OLIVIA']);
- print "======================\n";
- /*
- * 皆が選択している色だけを選らぶ
- * (論理積)
- */
- $common_col=0;
- $common_col=
- $peoples['LILY'] & $peoples['LOGAN'] & $peoples['OLIVIA'] ;
- printf("common colors int:% 4d bit:%08b\n", $common_col, $common_col);
- chkSelections($common_col);
- print "======================\n";
- /*
- * 選択されている全ての色を選ぶ
- * (論理和)
- */
- $common_col=0;
- $common_col=
- $peoples['LILY'] | $peoples['LOGAN'] | $peoples['OLIVIA'] ;
- printf("common colors int:% 4d bit:%08b\n", $common_col, $common_col);
- chkSelections($common_col);
- exit;
- /*
- * ビットが立っているものを探す
- */
- function chkSelections($selections)
- {
- global $items;
- foreach ( $items as $col_name => $col_num )
- {
- $chk_bit=( 1 << $col_num );
- if( $selections & $chk_bit ) // ビットが立ってる
- {
- printf("Select color:% 6s\n", $col_name);
- }
- }
- }
シフト演算でビットが立っているところを探していく方法もあるけど。
- $col_num=0;
- while( $selections )
- {
- if( $selections & 1 )
- {
- printf("Select color number:%d bit:%08b\n", $col_num, $selections);
- }
- $selections = $selections >> 1;
- $col_num++;
- }
MySQL
選択情報をMySQLに格納して、クエリで取得することもできる。
SELECT * hoge WHERE select_bit & ${col_num} ;
これでその色を選択している情報が引っ張れるです。