这听起来很简单,但由于某种原因,它不能完成我的工作。 我有一个数组,它将检查值是否存在然后将采取相应的行动
我的数组包含值,我的条件是检查2个条件,如果数组索引0处的数组中包含值“a”,并且数组中不存在“b”,则执行此操作。如果索引0处的值“a”和“b”确实存在,则运行另一个代码块。
//THIS CONTAINS ALL THE FIELDS SELECTED
$report_cols = $_POST['report_cols'];
$percent_amt= explode(",",$report_cols);
$n_fields_arr = array();
$b=0;
//This checks if b exists in array
if (array_key_exists('`b`', $percent_amt))
{
$b = 1;
}
if($percent_amt[0] == '`a`' && $b == 0)
{
$report_cols = str_replace("`a`,","",$report_cols);
$report_cols = str_replace(",`a`","",$report_cols);
$report_cols = str_replace(",,",",",$report_cols);
array_push($n_fields_arr,"a");
echo "done";
}
if($percent_amt[0] == '`a`' && $b == 1)
{
$report_cols = str_replace("`a`,","",$report_cols);
$report_cols = str_replace(",`a`","",$report_cols);
$report_cols = str_replace(",,",",",$report_cols);
$report_cols = str_replace("`b`,","",$report_cols);
$report_cols = str_replace(",`b`","",$report_cols);
$report_cols = str_replace(",,",",",$report_cols);
array_push($n_fields_arr,"a","b");
echo "Done AB";
}
我遇到的错误是它没有把两个&&& section并继续运行第一个if语句。如果有遗漏的东西或更好的方法,我们会非常感谢您的帮助
答案 0 :(得分:2)
explode()
函数使用数字键爆炸数组。
使用in_array()
检查b
。
if (in_array('b', $percent_amt))
{
$b = 1;
}
答案 1 :(得分:0)
您可以使用strpos搜索字符串中字符串的出现位置。 并使用数组作为str_replace的搜索参数。这将简化您的代码。
//$report_cols = $_POST['report_cols'];
$report_cols = '`a`,`foo`,`a`,`b`,`bar`,`b`,';
$n_fields_arr = array();
$b_found = strpos($report_cols, '`b`') !== false ? true : false;
$a_start = strpos($report_cols, '`a`') == 0 ? true : false;
if ($a_start) {
$report_cols = str_replace(array('`a`','`b`'), '', $report_cols);
$report_cols = trim(preg_replace('/,+/', ',', $report_cols), ',');
$n_fields_arr[] = 'a';
if ($b_found) {
$n_fields_arr[] = 'b';
}
}
print $report_cols;
var_dump($n_fields_arr);
输出:
`foo`,`bar`
array (size=2)
0 => string 'a' (length=1)
1 => string 'b' (length=1)