简体   繁体   中英

Implode comma in the i-th row of two-dimensional array

The array $solution is two-dimensional. I need to save its content to SQL table. However, before saving, I need to check that $solution[i][0] belongs to the result of the query SELECT num_arr FROM Schedule WHERE num_arr<>'' .

The problem is with the line $vals = implode(...) . How do I implode comma in the i-th row of the array $solution ? Now this line results in the string 0,0,0,0 instead of correct values.

    $columns_land = array("`num_arr`","`start`","`fin`","`way`");
    $cols_land = implode(",",$columns_land);

    for($i=0; $i<sizeof($solution); $i++) {
            $vals = implode(',', array_map('implode_comma', $solution[$i]));
            query_land = "INSERT INTO `Sequence` (" . $cols_land . ") 
                          VALUES " . $vals . " 
                          WHERE num_arr='".$solution[$i][0]."' 
                          AND num_arr IN (SELECT num_arr FROM Schedule WHERE num_arr<>'')";

            $result_land = execute_query($query_land);
    }

    function implode_comma($arr) {
        return '(' . implode(',', $arr) . ')';
    }

This statement has me confused:

$vals = implode(',', array_map('implode_comma', $solution[$i]));

Since implode_comma() expects an array, each item in $solution[$i] must also be an array; but that means $solutions itself must be a three-dimensional array.

I think you can just write this inside your loop instead:

$vals = implode(',', $solution[$i]);
$query_land = "INSERT INTO `Sequence` ($cols_land) 
    VALUES ($vals)
    WHERE num_arr='".$solution[$i][0]."' 
    AND num_arr IN (SELECT num_arr FROM Schedule WHERE num_arr<>'')";

$result_land = execute_query($query_land);

Btw, you should properly escape the variables you use in SQL, but I can't tell which database layer you're using, so I leave that up to you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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