PHP-为MySQL实现多维数组


PHP - Implode multi-dimensional array for MySQL

我正试图内爆一个包含字符)(的多维数组,以便我可以使用类似的查询:

插入表temp(a、b、c)值('a','b','c'),('d','e','f');

下面是一个多维数组的例子:

    $tmp = array(
              array(0 => 'CompanyB',
                    1 => 'IndustryA',
                    2 => 'Sysadmin',
                    3 => '01',
                    4 => '2011',
                    5 => '12',
                    6 => '2012',
                    7 => 'aeere',
                    8 => 'R6000',
                    9 => 'asdfasdf'),
              array(0 => 'CompanyC',
                    1 => 'IndustryC',
                    2 => 'Aabb',
                    3 => '02',
                    4 => '2012',
                    5 => '01',
                    6 => '2013',
                    7 => 'asdf',
                    8 => 'R7000',
                    9 => 'adfasdfeeeeeeeeeeeeeee'),
              array(0 => 'CompanyD',
                    1 => 'IndustryARR',
                    2 => 'NJNNLK',
                    3 => '01',
                    4 => '2011',
                    5 => '01',
                    6 => '2012',
                    7 => 'Anotheron',
                    8 => 'R9000',
                    9 => 'qweqweqwe'));

这不会产生任何结果,print implode("),(",$tmp);

我不是专业的php开发人员,也许有一种更简单的方法可以做到这一点。感谢您的意见。

您需要挖掘数组的第二级。

一种解决方案:

foreach($tmp as $v){
 echo "(".implode("),(",$v).")";
}

试试这个:

$rows = array(); // will hold all table rows to insert
foreach ($tmp as $row) { // loops through your datasets
    $row_string = ''; // will hold the string for this row
    foreach ($row as $value) {
        // make sure that value is escaped
        $row_string .= '"' . addslashes($value) . '", ';
    }
    $row_string = '(' . substr($row_string, 0, -2) . ')'; // trim last ", " and wrap in brackets
    $rows[] = $row_string; // push row to rows array
}
$rows = implode(', ', $rows); // glue rows together into one string