Use PHP array and bring results in multiple rows

Asked

Viewed 128 times

0

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

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

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

(3, 1),
(3, 2)

How can I do that?

I tried that, but you repeated the 2:

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

The result of what I did:

(3,2),(3,2)
  • Could describe in the question what he tried to do and the result obtained?

  • opa, I put there what I did

  • You are overwriting the variable $todos within the loop.

1 answer

2


The problem is that you are overwriting the variable $todos inside 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 function array_map:

$todos = join(',', array_map(function ($clima) use ($id) {
    return "({$id}, {$clima})";
}, $_POST['form']['clime']);
  • gave it right, only changed, the last climate you wrote clime and missed to close a parentheses last, then gave the right array_map, thanks!

  • For aggregation only, Join is a nickname for implode http://php.net/manual/en/function.implode.php

Browser other questions tagged

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