Use PHP array and bring results in several lines

0

I have an array $_POST['form']['clima'] which in this example has the value below

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

I need to get these values to join with $ id (in this example it will be 3) to bring the result below ($ id, value of each array):

(3, 1),
(3, 2)

How can I do this?

I tried this, but repeated the value 2:

$id = 3;
foreach($_POST['form']['clima'] as $clima){
$todos = '('.$id.','.$clima.')';
$todos.=','.$todos;
}

Result of what I did:

(3,2),(3,2)
    
asked by anonymous 20.10.2018 / 00:34

1 answer

2

The problem is that you are overwriting the $todos variable within your side, discarding the old values:

$id = 3;

foreach($_POST['form']['clima'] as $clima){
    $todos = '('.$id.','.$clima.')';  // ERRADO
    $todos.=','.$todos;
}

You need to use different variables or concatenate directly:

$id = 3;
$todos = '';

foreach ($_POST['form']['clima'] as $clima) {
    $todos .= '('.$id.','.$clima.')';
}

But the simplest is to use the array_map function:

$todos = join(',', array_map(function ($clima) use ($id) {
    return "({$id}, {$clima})";
}, $_POST['form']['clime']);
    
20.10.2018 / 01:01