How to get 2 PHP arrays and join in 1 string

5

I have 2 arrays in PHP 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" } 

How can you put them together in a variable that is like this?

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

With this I will make a INSERT in the MYSQL table that should look like this:

INSERT INTO tabela (qtd, ing) VALUES (1,'a'), (2,'b');
    
asked by anonymous 10.09.2018 / 21:42

2 answers

5

You can use array_map() to get the respective values of each array (peer-to-peer) and within the anonymous function mount the format and / or sanitize the string. Since the function return is a new array, use the implode() function to separate all elements by vrigula 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);

Output:

('1', 'a'),('2', 'b'),('3', 'c')
    
10.09.2018 / 22:13
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 array_map function:

$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 turn an array in the format (1, a) , so 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, only use join again:

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

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

Note that the a and b values do not have quotation marks, which may break the syntax of your SQL if not handled correctly.

    
10.09.2018 / 22:17