PHP how to loop through a post array

后端 未结 6 1055
北恋
北恋 2020-11-30 10:31

I need to loop through a post array and sumbit it.

#stuff 1



        
相关标签:
6条回答
  • 2020-11-30 10:51
    for ($i = 0; $i < count($_POST['NAME']); $i++)
    {
       echo $_POST['NAME'][$i];
    }
    

    Or

    foreach ($_POST['NAME'] as $value)
    {
        echo $value;
    }
    

    Replace NAME with element name eg stuff or more_stuff

    0 讨论(0)
  • 2020-11-30 10:52

    You can use array_walk_recursive and anonymous function, eg:

    $sweet = array('a' => 'apple', 'b' => 'banana');
    $fruits = array('sweet' => $sweet, 'sour' => 'lemon');
    array_walk_recursive($fruits,function ($item, $key){
        echo "$key holds $item <br/>\n";
    });
    

    follows this answer version:

    array_walk_recursive($_POST,function ($item, $key){
        echo "$key holds $item <br/>\n";
    });
    
    0 讨论(0)
  • 2020-11-30 10:53

    I have adapted the accepted answer and converted it into a function that can do nth arrays and to include the keys of the array.

    function LoopThrough($array) {
        foreach($array as $key => $val) {
            if (is_array($key))
                LoopThrough($key);
            else 
                echo "{$key} - {$val} <br>";
        }
    }
    
    LoopThrough($_POST);
    

    Hope it helps someone.

    0 讨论(0)
  • 2020-11-30 10:55

    Likely, you'll also need the values of each form element, such as the value selected from a dropdown or checkbox.

     foreach( $_POST as $stuff => $val ) {
         if( is_array( $stuff ) ) {
             foreach( $stuff as $thing) {
                 echo $thing;
             }
         } else {
             echo $stuff;
             echo $val;
         }
     }
    
    0 讨论(0)
  • 2020-11-30 10:57

    For some reason I lost my index names using the posted answers. Therefore I had to loop them like this:

    foreach($_POST as $i => $stuff) {
      var_dump($i);
      var_dump($stuff);
      echo "<br>";
    }
    
    0 讨论(0)
  • 2020-11-30 11:05

    This is how you would do it:

    foreach( $_POST as $stuff ) {
        if( is_array( $stuff ) ) {
            foreach( $stuff as $thing ) {
                echo $thing;
            }
        } else {
            echo $stuff;
        }
    }
    

    This looks after both variables and arrays passed in $_POST.

    0 讨论(0)
提交回复
热议问题