简体   繁体   中英

How to loop through appended inputs inside an array

I'm submitting appended inputs through an API. The number of items is different every time. When I submit the form, the input is submitted successfully and an object is returned, but only the last appended input is submitted. How can I run a loop inside of the array shown, or what syntax of loop works here so that I will submit a new item for each appended input? thank you for considering.

<script>
$(document).ready(function(){
    $("#new").click(function(){
        $("table").append("<tr><td><input type= 'text' name = 'item[]'</td> </tr>");
    });
});
</script>

<?php 

after a form/table with input name="item[]" my PHP:

if (isset($_POST['submit']))
{
   $size = sizeof($_POST['item']);
   for ($i = 0; $i < $size; $i++)  
   {
      $product = $_POST['item'][$i];
   }
   $fields = array(
      'customer' => 992058,
      'items' => [
                    [
                        'name' => $product,
                    ]
                 ]
   );

// HERE IS A CURL CALL that POSTS $fields AND RETURNS JSON
?>

the JSON I'd like to see returned might look something like

"items":[{"name":"product1"}][{"name":"product2"}];

instead of what I'm getting which is

"items":[{"name":"product2"}]

Here is what you need to:

if (isset($_POST['submit']))
    {

        $size = sizeof($_POST['item']);
        $products = [];

        for ($i = 1; $i < $size; $i++)  

            {

                $products[]['name'] = $_POST['item'][$i];
            }

            $fields = array(

                        'customer' => 992058,


                        'items' => $products
                            );

The problem with your code that var $product get only the last insert while running through the loop, you need to create an array inside the loop.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM