4

I have the following form, with fields:

  • From
  • To
  • Price

You can add multiple rows and this data is then sent to the controller.

What I want is:

Let's assume there are two rows of inputs currently on the page, the output would therefore be something like:

$rates => array(2)
   0 => [ 
      "from" => 1, 
      "to"   => 2,
      "price" => 10
   ], 
   1 => [ 
      "from" => 1, 
      "to"   => 2,
      "price" => 10
   ]   

I have tried to do the following (HMTL):

  <input type="text" name="rates[]" placeholder="Enter rate from" 
  autocomplete="off" class="form-control">

But this just gives me an array of 6 with all the values, with no way of knowing the order. I have also tried the following:

<input type="text" name="rates[]['from']" placeholder="Enter rate from" 
      autocomplete="off" class="form-control">

 <input type="text" name="rates[]['to']" placeholder="Enter rate to" 
      autocomplete="off" class="form-control">

 <input type="text" name="rates[]['price']" placeholder="Enter rate price" 
      autocomplete="off" class="form-control">

This isn't producing the result(s) that I need. Is it possible to do what I want to do using HTML and PHP?

4
  • this you try rates[index]['from'] Commented Jun 13, 2017 at 9:44
  • @HoàngĐăng Would index be a number? Commented Jun 13, 2017 at 9:44
  • yes, you can generate more input field by js Commented Jun 13, 2017 at 9:49
  • <input type="text" name="rates[0]['from']" placeholder="Enter rate from" autocomplete="off" class="form-control"> Commented Jun 13, 2017 at 9:50

1 Answer 1

9

Instead of using an index-based approach, you can use three different arrays (from, to and prices e.g.). You can then iterate through all of them to get your values.

HTML

<input type="text" name="from[]" placeholder="Enter rate from" 
      autocomplete="off" class="form-control">

 <input type="text" name="to[]" placeholder="Enter rate to" 
      autocomplete="off" class="form-control">

 <input type="text" name="prices[]" placeholder="Enter rate price" 
      autocomplete="off" class="form-control">

PHP

 $from = [
        'Jane',
        'Bob',
        'Mary',
    ];
    $to = [
        'John',
        'Alex',
        'Paul',
    ];
    $prices = [
        10,
        2500,
        2,
    ];

  $finalValues = [];
  foreach ($prices as $i => $price) {
    $finalValues[
              "from" => $from[i];
              "to" => $to[i];
              "price" => $price;
  } 

This only works when your values are all required or give back null when not set

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

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.