MindTheGap
MindTheGap

Reputation: 193

Parse an array in php posted by an html form

I have the following problem. I have these types of select inside my form:

<select name="variation[8][]" multiple>
   <option value="1">s</option>
   <option value="2">m</option>
   <option value="3">l</option>
</select>

<select name="variation[9][]" multiple>
   <option value="8">red</option>
   <option value="9">blue</option>
   <option value="10">black</option>
</select> 

I want to read the posted array properly with php and I want to write this in the database:

variation_id => 8 
variation_term => 1 
variation_id => 8 
variation_term => 2 
variation_id => 8 
variation_term => 3 

variation_id => 9 
variation_term => 8 
variation_id => 9 
variation_term => 9 
variation_id => 9 
variation_term => 10

How can I parse this array posted? There is a better way to do this?

TNX

I have found this solution:

foreach ($_POST['variation'] as $key => $value) {
   for($i=0; $i<count($value); $i++){
     echo "varitaion name = $key"."<br>";
     echo "value = $value[$i]";
   }
}

Upvotes: 1

Views: 1423

Answers (1)

Nouphal.M
Nouphal.M

Reputation: 6344

Try

foreach($_POST['variation'] as $key=>$val){
  if(is_array($val)){
     echo " Values for $key Are:"; // get your variation index eg:8,9 etc
     foreach($val as $key1=>$val1){
         echo $val1.","; // get the index values
     }
         echo "<br/>";
  }
}

Upvotes: 1

Related Questions