Php 字符串到布尔值的转换。。。工作在4位,但不是8位
试图组合一个php程序,读取一个“menu”整型变量(通过URL传递),将其转换为二进制字符串。。。然后读取字符串中的每个布尔值并将其添加到数组中 适用于4位(尽管可能效率不高)。。。。但对8位不起作用Php 字符串到布尔值的转换。。。工作在4位,但不是8位,php,Php,试图组合一个php程序,读取一个“menu”整型变量(通过URL传递),将其转换为二进制字符串。。。然后读取字符串中的每个布尔值并将其添加到数组中 适用于4位(尽管可能效率不高)。。。。但对8位不起作用 <?php $menubin = decbin($_GET['menu']); $menulen = strlen($menubin)-1; for($x=$menulen; $x > -1; $x--) { $array = $menulen-$x; $menuboo
<?php
$menubin = decbin($_GET['menu']);
$menulen = strlen($menubin)-1;
for($x=$menulen; $x > -1; $x--)
{
$array = $menulen-$x;
$menubool[$array] = substr($menubin,$x,1);
}
if($menubool[0] == '1') { ... }
if($menubool[1] == '1') { ... }
if($menubool[2] == '1') { ... }
if($menubool[3] == '1') { ... }
if($menubool[4] == '1') { ... }
if($menubool[5] == '1') { ... }
if($menubool[6] == '1') { ... }
if($menubool[7] == '1') { ... }
?>
您可以执行以下操作:
$int = 37; // for example
$bits = array();
$str = str_pad(decbin($int),8,"0",STR_PAD_LEFT);
for ($i=0; $i<=7; $i++){
$bits[7-$i] = substr($str,$i,1);
}
var_dump($bits);
$int=37;//例如
$bits=array();
$str=str_pad(decbin($int),8,“0”,str_pad_左);
对于($i=0;$i,假设您的$menubin
字符串看起来像0100
。这可以通过和switch语句实现。这种方法将给您一些灵活性,允许您任意选择菜单项
<?php
//string of selections
$string = "1011";
// result of bitshift on string
$bits = 0;
for($i = strlen($string); $i >= 0; $i -= 1){
$bits += (int)$string[$i] << $i;
}
// arbitrarily make selections and cases as you add menu items
switch($bits) {
case 1:
echo "menu item 1";
break;
case 2:
echo "menu item 2";
break;
case 4:
echo "menu item 3";
break;
case 8:
echo "menu item 4";
break;
case 13:
echo "menu item 1, 3 and 4";
break;
}
?>
不确定您的问题是什么,但是您可以简化整个if
行,只需:if(在数组(1,$menubool)中){}
。世界上有10种人。懂二进制的人和不懂二进制的人。解决了这个问题。这是一个字符串长度问题。阿马尔干杯,我们将研究如何提高ifs的效率1011
不是13,而是11-您正在反向读取(或写入)位模式。