How to take 2 PHP arrays and join in 1 string

Asked

Viewed 446 times

5

I have 2 PHP arrays that come from a form $_POST['qtd'] and $_POST['ing']:

array(2) { [0]=> string(1) "1" [1]=> string(1) "2" } 
array(2) { [0]=> string(1) "a" [1]=> string(1) "b" } 

It has, somehow, to join them into a variable that was like this?

$variavel = "(1,'a'), (2,'b')";

With that I’ll make one INSERT in the MYSQL table that should look like this:

INSERT INTO tabela (qtd, ing) VALUES (1,'a'), (2,'b');
  • 1

    Will generate an sql with this? at least has face.

  • And parentheses are part of string? could format exactly how accurate the result?

  • this, I will do a mysql Insert, will look like this: INSERT INTO table (Qtd, ing) VALUES (1,a), (2,b);

  • In the title you say you want to generate a string but the expected result is an array. You can clarify or edit the question?

  • 1

    yeah, I think the title was not clear mt, I will edit, but what I need is this, take the 2 arrays, to make an input in mysql

  • So your problem is another, not just joining in a string. It is likely that @rray is already formulating an answer, but it is more advisable to use prepared statements for safety and because it is more practical. Are you using which extension to make the connection? PDO, mysqli or any other?

Show 1 more comment

2 answers

5


Can use array_map() to take the repective values of each array (par to par) and within the anonymous function assemble the format and/or sanitize the string. Since the function return is a new array, use the function implode() to separate all elements by comma in the generated string:

$arr1 = array(1,2,3);
$arr2 = array('a', 'b', 'c');

$valores = array_map(function($a, $b){ return sprintf("('%s', '%s')", $a, $b);}, $arr1, $arr2);

echo implode(',', $valores);

Exit:

('1', 'a'),('2', 'b'),('3', 'c')

4

You have:

$arr = [
    ['0', '1'],
    ['a', 'b']
];

First, we need to associate the values of the first array with the values of the second. You can do this with the function array_map:

$pares = array_map(null, ...$arr);

Getting, like this:

Array
(
    [0] => Array
        (
            [0] => 0
            [1] => a
        )

    [1] => Array
        (
            [0] => 1
            [1] => b
        )

)

Each pair will need to flip an array into the format (1, a), then instead of null we create a function:

$pares = array_map(function (...$parameters) {
    return '(' . join(', ', $parameters) . ')';
}, ...$arr);

Getting, like this:

Array
(
    [0] => "(0, a)"
    [1] => "(1, b)"
)

Then just use the join:

$resultado = join(', ', $pares);

Getting the string "(0, a), (1, b)".

Realize that the values a and b have no quotes, which can break your SQL syntax if not handled correctly.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.