我正在查询一个数据库,它返回一个长整数布尔值。例如 0011000000000100001000000010000000000100000000000000。
1 个值中的每一个都等同于一个字符串。例如空调或动力转向。如果值为 0,则 Vehicle 没有此选项。
我正在尝试找出一种方法来遍历这个大整数并返回汽车拥有的每个“选项”的名称。
我对 PHP 非常陌生,如果有人有解决方案,我将非常感谢您的帮助。
非常感谢安德鲁
我正在查询一个数据库,它返回一个长整数布尔值。例如 0011000000000100001000000010000000000100000000000000。
1 个值中的每一个都等同于一个字符串。例如空调或动力转向。如果值为 0,则 Vehicle 没有此选项。
我正在尝试找出一种方法来遍历这个大整数并返回汽车拥有的每个“选项”的名称。
我对 PHP 非常陌生,如果有人有解决方案,我将非常感谢您的帮助。
非常感谢安德鲁
这很可能是一个字符串,您可以遍历它并为每个字符串在地图中查找名称:
$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
演示在这里。数组中有空选项,因为选项映射不完整。它正确填写了“Power Steering”和“Brakes”,对应1于字符串中的前两个。
我会推荐这样的东西。
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
}
    使用位运算符。
就像是:
$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
您也可以使用右移>>运算符并按 2 的幂进行运算,但我并没有无聊到编写该代码。