Foreach loop with multiple arrays

前端 未结 7 1871
南旧
南旧 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:30

    Although you already selected an answer, don't forget this piece of script may fail if the POST values are not arrays. You can overcome this with a small piece of code:

    $something = is_array($_POST['something']) ? $_POST['something'] : array();
    $example = is_array($_POST['example']) ? $_POST['example'] : array();
    
    /* Get all the keys from both arrays
     * If they don't share the keys, none will be lost
     */
    $keys = array_merge(array_keys($something),array_keys($example));
    $keys = array_unique();
    
    if (count($keys)) {
        $sql = 'INSERT INTO table (row, row2) VALUES ';
        $values = array();
    
        foreach ($keys as $key) {
            // Single quotes for PHP, we are not expanding variables
            // If the element cannot be converted into a string, don't show the error on screen
            $values[] = '("' . @mysql_real_escape_string($something[$key]) . '","' . @mysql_real_escape_string($example[$key]) . '")';
        }
    
        $sql .= implode(',', $values);
        mysql_query($sql);
    }
    

提交回复
热议问题