有没有办法转换像这样的数组:
Array ( [level-1] => 2 [quarter-1] => 1 [year-1] => 2014 [level-2] => 2 [quarter-2] => 2 [year-2] => 2015 [level-49] => 2 [quarter-49] => 2 [year-49] => 2015 [level-58] => 1 [quarter-58] => 1 [year-58]
并仅使用关键字后面的数字在sql表中使用它们。例如,表格如下所示:
ID 1 Level 2 Quarter 1 Year 2014
ID 2 level 2 quater 2 Year 2015
ID 49 level 2 quarter 2 year 2015
等
我试过
if(!empty($_POST)){
print_r ($_POST);
echo "<br/><br/>";
$s=$_POST;
echo $abc= implode(',', $s);
for($a=0;$a<count($s);$a++){
$ar=explode(',',$abc);
echo $var=$ar[$a];
}
}
但我得到的结果是:
2,1,2014,2,2,2015,2,2,2015...
我还需要显示ID。但我最重要的是不知道如何解释结果将它们放入数据库..
答案 0 :(得分:3)
试试这个:
$array = array ( "level-1" => 2, "quarter-1" => 1, "year-1" => 2014, "level-2" => 2, "quarter-2" => 2, "year-2" => 2015, "level-49" => 2, "quarter-49" => 2, "year-49" => 2015, "level-58" => 1, "quarter-58" => 1, "year-58"=>2016);
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 2 Quarter 1 Year 2014
ID 2 Level 2 Quarter 2 Year 2015
ID 49 Level 2 Quarter 2 Year 2015
ID 58 Level 1 Quarter 1 Year 2016
答案 1 :(得分:0)
我不知道用PHP编写代码,所以我会向你解释这样做的逻辑。
for(int i=0;i<array.length;i=i+3)
{
// get value from array[i]; get the level-x field and retrieve the x value, then extract integers accordingly from it after keywords. In java StringTokenizer can be used for this, or regex etc
// again get value from array[i+1] and extract the integer
// get the value from array[i+2] and do the same as above.
}
如果数组被洗牌,您可以将它与level-x匹配以获得要插入的确切元组。所以level-x,x值充当一个对所有相关值进行分组的索引。