dongpian4954
2017-11-27 10:35 浏览 42
已采纳

如何每次迭代两个数组中的每一个项目,而不是循环遍历PHP中动态html输入的完整循环

I'm having two arrays of fields (id[], names[]) and I want to loop through one item each of the two array per time instead of looping through the complete cycle of id[] before looping through names[] using php

HTML Code

<input type="text" name="id[]" /> &nbsp; &nbsp; <input type="text" name="names[]" /></br>
 <input type="text" name="id[]" /> &nbsp; &nbsp; <input type="text" name="nmaes[]" /></br>
 <input type="text" name="id[]" /> &nbsp; &nbsp; <input type="text" name="names[]" /></br>

PHP Code

<?php
error_reporting( error_reporting() & ~E_NOTICE );
if($_POST['test']=='test')
{
    foreach($_POST['id'] as $key => $value) {
    echo "id $key = $value"."</br>";
}
foreach($_POST['names'] as $key => $value) {
    echo "names $key = $value"."</br>";
}


}

?>

Thanks.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

2条回答 默认 最新

  • 已采纳
    douxian6086 douxian6086 2017-11-27 10:40

    You can count number of element and use it to get your posted data. It's not really nice but that should work.

    Warning, id and name need to be same size!

    if($_POST['test']=='test')
    {
        $count = count($_POST['id']);
        for ($i=0;$i<$count;$i++) {
            $id = $_POST['id'][$i];
            $name = $_POST['name'][$i];
            echo "id $i = $id"."</br>";
            echo "name $i = $name"."</br>";
        }
    }
    

    Other way

    if($_POST['test']=='test')
    {
        foreach ($_POST['id'] as $i => $id) {
            $name = $_POST['name'][$i];
            echo "id $i = $id"."</br>";
            echo "name $i = $name"."</br>";
        }
    }
    
    点赞 评论 复制链接分享
  • dongsuiying7773 dongsuiying7773 2017-11-27 10:45

    You can do this setting name="user[index][id]"/name="user[index][name] to name of inputs. Index is variable

    <input type="text" name="user[0][id]"> &nbsp; &nbsp; <input type="text" name="user[0][name]"></br>
    <input type="text" name="user[1][id]"> &nbsp; &nbsp; <input type="text" name="user[1][name]"></br>
    <input type="text" name="user[2][id]"> &nbsp; &nbsp; <input type="text" name="user[2][name]"></br>
    

    And PHP like that

    <?php
        foreach($_POST['user'] as $user) {
            echo 'id = ' . $user['id'] . '<br> name = ' . $user['name'] . '<br>';
        }
    ?>
    
    点赞 评论 复制链接分享

相关推荐