简体   繁体   English

如何遍历数组中的附加输入

[英]How to loop through appended inputs inside an array

I'm submitting appended inputs through an API. 我正在通过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: 在输入名称为“ item []”的表单/表格之后,我的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 我想返回的JSON可能看起来像

"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. 您的代码中的问题是,var $product在循环中仅获得最后的插入,您需要在循环内创建一个数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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