4
$array = array
        (
            53 => array('num' => 20,'name' => 'aaa'),
            10 => array('num' => 20,'name' => 'bbb')
        );

$sql ="INSENT INTO data(id,num,name) VALUES('53','20','aaa'),('10','20','bbb') ";

How to convert $array to ('53','20','aaa'),('10','20','bbb') ?

Thanks

3 Answers 3

6

implode() can help you do this, though you will need to loop through and apply it to each individual array:

 $resultStrings = array();
 foreach ($array as $key => $values) {
    $subarrayString = "('$key','" . implode($values, "','") . "')";
    $resultStrings[] = $subarrayString;
 }
 
 $result = implode($resultStrings, ",");
Sign up to request clarification or add additional context in comments.

4 Comments

implode($array, "','") -> implode($subarray, "','") thanks
Yep, sorry, missed that one before I posted. Just updated my answer.
I like the second implode there! Watch out, though, the poster wanted the key of the array in there as well. You'd need to loop $array as $key=>$subarray and concatenate the key before the imploded subarray
Very true! Man, I was not on it when I submitted that. Edited again.
1

I'd do this using a prepared statement and a simple loop, eg

$db = new PDO(...);
$stmt = $db->prepare('INSERT INTO data(id, num, name) VALUES (?, ?, ?)');
$stmt->bindParam(1, $id);
$stmt->bindParam(2, $num);
$stmt->bindParam(3, $name);

foreach ($array as $id => $vals) {
    $num = $vals['num'];
    $name = $vals['name'];
    $stmt->execute();
}

3 Comments

Won't this execute once per array? I'd avoid any more roundtrips to the database than strictly needed.
This will hit the DB once per outer array element, however the statement is prepared and thus bind values/arguments are communicated in reduced traffic and the DB has already parsed the SQL statement. It might come down to 6|half-dozen/one-or-the-other scenario, but this method is well-known pattern and compatible across DB platforms vs. the compound values for a MySQL insert statement.
@Justin not to mention the benefits of using parameter binding.
0

loop through them using foreach:

$result = '';
foreach ($array as $key=>$subarray) {
    $result .= "('$key'";
    foreach ($subarray as $el) {
        $result .= ",'$el'";
    }
    $result .= "),";
}
//get rid of the trailing comma
$result = substr($result,0,-1);

et voilá

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.