我从PHP中的Array
操作得到以下POST
:
Array (
[level-1] => 3
[quarter-1] => 1
[year-1] => 2014
[level-2] => 4
[quarter-2] => 2
[year-2] => 2014
[level-53] => 2
[quarter-53] => 1
[year-53] => 2013
[level-58] => 3
[quarter-58] => 2
[year-58] => 2014
[action] => store
[submit_values] => Store
)
我执行以下操作以从Array获取值:
$array=$_POST;
foreach(array_chunk($array,3,true) as $val){
foreach($val as $k=>$v){
if(strpos($k, "level") !== false){
$temp = explode("-",$k);
$id = $temp[1];
$level = $v;
}
if(strpos($k, "quarter") !== false){
$quarter = $v;
}
if(strpos($k, "year") !== false){
$year = $v;
}
}
echo "ID ".$id." Level ".$level." Quarter ".$quarter." Year ".$year;
echo "<br>";
}
但我得到的是以下内容:
ID 1 Level 3 Quarter 1 Year 2014
ID 2 Level 4 Quarter 2 Year 2014
ID 53 Level 2 Quarter 1 Year 2013
ID 58 Level 3 Quarter 2 Year 2014
ID 58 Level 3 Quarter 2 Year 2014
最后一行重复!我在代码中做错了什么?
答案 0 :(得分:0)
试试这个:
$array = $_POST;
unset($array['submit_values']);
unset($array['action']); //...
答案 1 :(得分:0)
您不会检查action
和submit_values
的最后一个循环,因此会返回上次保存的值:
$array=$_POST;
foreach(array_chunk($array,3,true) as $val){
foreach($val as $k=>$v){
if(strpos($k, "level") !== false){
$temp = explode("-",$k);
$id = $temp[1];
$level = $v;
}
elseif(strpos($k, "quarter") !== false){
$quarter = $v;
}
elseif(strpos($k, "year") !== false){
$year = $v;
}
// if not one of ifs works
else continue;
}
echo "ID ".$id." Level ".$level." Quarter ".$quarter." Year ".$year;
echo "<br>";
}
在循环后重置值也总是更好:
foreach(array_chunk($array,3,true) as $val){
$id = '';
$level = '';
$quarter = '';
$year = '';
答案 2 :(得分:0)
当循环通过 [action] =&gt; store 和 [submit_values] =&gt;存储,控件不会进入任何if语句,因此在最后2个循环中,它会打印先前设置的值
即,ID 58 Level 3 Quarter 2 Year 2014年
<强>解决方案:强>
尝试将 ID ,级别,季度和年度重新初始化为 “”( foreach循环结束时的空白值 。