2013-08-26 50 views
2

我在查询一个数据库,它返回一个长整数的布尔值。例如0011000000000100001000000010000000000100000000000000.来自php整数的布尔值

1个值中的每一个等同于一个字符串。例如。空调或动力转向。如果该值为0,则车辆不具有此选项。

我想找出一种方法来循环这个大整数,并返回该车的每个“选项”的名称。

我对PHP很陌生,非常感谢帮助,如果任何人有解决方案。

非常感谢 安德鲁

+0

它是一个整数或布尔值?他们是两种不同的演员类型 –

回答

3

这是最有可能的一个字符串,您可以通过它和每一个刚迭代,在地图查找名称:

$option_map = array(
    'Air Conditioning', 
    'Sun roof', 
    'Power Steering', 
    'Brakes', 
    //.. Fill with all options 
    // Could populate from a database or config file 
); 

$str = '0011000000000100001000000010000000000100000000000000'; 
$strlen = strlen($str); 
for($i = 0; $i < $strlen; $i++){ 
    if($str[$i] === '1'){ 
    $options[] = $option_map[$i]; 
    } 
} 

// $options is an array containing each option 

Demo Here。数组中有空选项,因为选项图不完整。它正确地填写了“动力转向”和“制动器”,对应于字符串中的前两个1

0

我会推荐这样的东西。

  1. 循环通过串
  2. 分配在阵列中(然后可以稍后访问任何项目阵列中的,或通过整个阵列,其可以拉你的值的另一功能的每个选项的长度。
  3. 创建这样的功能如get_car_option并传递位置以及值
//force the value to be a string, where $longint is from your DB 
$string = (string) $longint; 

for($i=0; $i<strlen($string); $i++) 
{ 
    $array[$i] = get_car_option($i, substr($string, $i, 1)); 
} 

//example of function 
function get_car_option($pos, $value) 
{ 
    //you can then use this function to get the 
    //...values based on each number position 
} 
0

使用bitwise operators

喜欢的东西:

$myVal = 170; //10101010 in binary 

$flags = array(
    'bumpers' => 1,  //00000001 
    'wheels' => 2,  //00000010 
    'windshield' => 4, //00000100 
    'brakes' => 8,  //00001000 
    ... 
); 

echo "The car has: "; 

foreach($flags as $key => $value) { 
    if($myVal & $value) { 
    echo $key . " and "; 
    } 
} 

// Output: Car has: wheels and brakes and 

你也可以使用右移>>运营商,通过两个大国去,但我没有足够的无聊编写代码。