2

I want to know the best and easiest way to pass associative array in form inside input field. So far Ive done this and it all started to look messy and hard to handle.

$dish_result = $obj->getAll_dish();// this returns array all the rows in dish table
<form action='order_process.php' method='post'>
   foreach ($dish_result as $dish){
     echo '<input id="" name="dish_name[]" type="checkbox" value="'. $dish['dish_name'].'">';
     echo '<input id="" name="dish_number[]" type="checkbox" value="'. $dish['dish_number'].'">';         
     }
</form>

Now on the order_process.php I have

 foreach($_POST['dish_name'] as $dish){
        echo $dish;
  }
 foreach($_POST['dish_number'] as $num){
       echo $num;
 }

What I wanted is an associative array, but how can I associate it the form dynamically. in other words I wanted to achieve this on the order_process.php.

 $dishes = array(
       //'dish_name' => dish_number
      'chickencurry' => '70',
      'onionbhajis'  =>  '22'
       // and so on. 
  );

Thank you very much in advance.

1
  • What happens if you change your foreach to include $key => $dish and set the inputs as name="dish_name[{$key}]".. ? That way you could map the values to their keys Commented Feb 18, 2015 at 1:57

2 Answers 2

1

Create a grouping name first, then to get that kind of structure, make the dish name as key, then the value attribute holds the number. The basic idea is this:

name="dish[dishname]" value="dish_number"

It'll be like this:

echo '<input id="" name="dish['.$dish['dish_name'].']" type="checkbox" value="'. $dish['dish_number'].'" />';

When you submit it with all the checkbox checked, it should be something like:

Array
(
    [chickencurry] => 1
    [onionbhajis] => 2
)

On the order_process.php page, just call it just like you normally do:

$dishes = $_POST['dish'];
foreach($dishes as $dish_name => $dish_number) {

}

Sample Output

Sign up to request clarification or add additional context in comments.

Comments

0

You can add an index to array postdata. Try this:

  foreach ($dish_result as $dish){
      echo '<input id="" name="dishes['.$dish['dish_name'].']" type="checkbox" value="'. $dish['dish_number'].'">'; 
  }

Your data will then be an associative array of the checked elements when posted back.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.