Reputation: 297
Is there any way to transform an array looking like this:
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]
and take only the numbers after the keywords to use them in an sql table. For example, the table would look like:
ID 1 Level 2 Quarter 1 Year 2014
ID 2 level 2 quater 2 Year 2015
ID 49 level 2 quarter 2 year 2015
Etc
I tried
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];
}
}
But the result i get is something like :
2,1,2014,2,2,2015,2,2,2015...
I need also the ID to be shown. But i most importantly do not know how to interpret the results to put them in the db..
Upvotes: 1
Views: 89
Reputation: 32710
Try this :
$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>";
}
Output :
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
Upvotes: 3
Reputation: 1685
I don't know to code in PHP, so i will explain you the logic for doing it.
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.
}
If the array is shuffled, you can match it with the level-x to get the exact tuple to insert. So level-x, the x value acts as an index that groups all related value.
Upvotes: 0