PHP - 用于MySQL的Implode多维数组

时间:2013-08-21 15:28:17

标签: php

我试图破坏一个包含)(字符的多维数组,以便 我可以使用类似这样的查询:

  

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

以下是multidimentional数组的示例:

    $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开发人员,也许有一个更简单的方法来做到这一点。 感谢您的意见。

2 个答案:

答案 0 :(得分:1)

你需要挖掘阵列的第二层。

一个解决方案:

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

答案 1 :(得分:0)

试试这个:

$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