Home > Mobile >  Imploding an array of arrays in php
Imploding an array of arrays in php

Time:10-14

I have the following array:

$names = [
    ['Joe','Moe','Joey'],
    ['John','Doe','Curly'],
    ['Jimmy','Fallon','Funny']
];

What I am trying to do, is implode into a string that looks like this:

"('Joe','Moe','Joey'),('John','Doe','Curly'),('Jimmy','Fallon','Funny')"

The implode function does not work on an array of arrays, so I did the following, and it accomplishes what I need:

$strings = [];
foreach ($names as $name) {
    $strings[] = '('.implode(',',$name).')';
}
$output = implode(',',$strings);

My question is: is there a cleaner way to do this?

CodePudding user response:

If you intend on using the array in SQL queries, you're on the wrong track. Instead...

  1. Prepare a statement
  2. Iterate the array and bind variables
  3. Execute the statement

For example

// PDO version
$stmt = $conn->prepare("INSERT INTO tableName VALUES (?, ?, ?)");
foreach ($names as $row) {
    $stmt->execute($row);
}

// MySQLi version because for some reason people keep using it
$stmt = $conn->prepare("INSERT INTO tableName VALUES (?, ?, ?)");
$stmt->bind_param("sss", $a, $b, $c);
foreach ($names as [ $a, $b, $c ]) {
    $stmt->execute();
}

Original answer below

A combination of implode() and array_map() should work

$output = implode(",", array_map(function($row) {
    return sprintf("(%s)", implode(",", array_map(function($name) {
        return "'$name'";
    }, $row)));
}, $names));

This includes the single-quotes around each name and wraps each group in parentheses.

Demo ~ https://3v4l.org/PLu1g

CodePudding user response:

When you are modifying data in a foreach loop that is a code smell. Usually you can use a reducer, map or something like that instead. That makes your code easier to understand.

$result = array_map( function($item) {
  return "('" . implode( "','", $item) . "')";
}, $names );
$result = '"'.implode( ',', $result ).'"';

If you use this code repeatably put it in a function or method that returns the string.

  •  Tags:  
  • php
  • Related