Foreach loop with multiple arrays

前端 未结 7 1872
南旧
南旧 2021-01-01 03:50

This is what I want:


foreach($_POST[\'something\'] as $something){
    foreach($_POST[\'example\'] as $example){
        $query = mysq         


        
7条回答
  •  梦谈多话
    2021-01-01 04:36

    $cnt = count($_POST['something']);
    $cnt2 = count($_POST['example']);
    
    if ($cnt > 0 && $cnt == $cnt2) {
        $insertArr = array();
        for ($i=0; $i<$cnt; $i++) {
            $insertArr[] = "('" . mysql_real_escape_string($_POST['something'][$i]) . "', '" . mysql_real_escape_string($_POST['example'][$i]) . "')";
        }
    
        $query = "INSERT INTO table (column, column2) VALUES " . implode(", ", $insertArr);
        mysql_query($query) or trigger_error("Insert failed: " . mysql_error());
    }
    

    Here is another method. This one uses extended inserts, so should be more efficient and quicker, and utilizes mysql_real_escape_string for security reasons. The count check is to just make sure that both fields have the same count, if not then I take this is a mishap. If they are allowed to have a different number of fields, you can simply use the isset() function to check to make sure they contain a value.

    EDIT

    This is assuming of course, that you do not want 'something' to iterate over all the 'example' values and be assigned to each one. If you want that well it is a bit of a change up.

    Added an insert array test, if there are no elements no need to update. Thanks Gumbo for that.

提交回复
热议问题