How to match four or more arrays?

Asked

Viewed 92 times

2

I would like to combine four or more array’s. With two array’s, I use the array_combine and I have the expected result, already with four, no.

Which function should I use to combine four array’s?

Follows my code:

HTML

<input type='text' id='nome' name='nome[]' />
<input type='text' id='email' name='email[]' />
<input type='text' id='idade' name='idade[]' />
<input type='text' id='altura' name='altura[]' /> 

PHP

$nome = $_POST['nome'];
$email = $_POST['email'];
$idade = $_POST['idade'];
$altura = $_POST['altura'];
$merg = array_merge($nome,$email,$idade,$altura);
foreach($merg as ... ) //aqui que está a minha dificuldade
{
    echo $nome; 
    echo $email;    
    echo $idade;
    echo $altura;   
}
  • The arrays indices are the same? the problem is that they are being overwritten.

  • Can you explain why you need to combine arrays? Is it because you have inputs with the same fields for different people? It would be interesting to understand better the function you need.

  • 1

    In the text you say that uses array_combine and in the example Voce uses merge arrary and inside the loop Voce uses the variables directly, without being by vector, could explain which the outworking you want to get with the script?

  • Sorry Guilherme, I realized that the array_combine does not combine more than two values, so I started to test with the array_merge. I have a form, where people are added dynamically with these four fields. After doing POST in the form, I would like to receive the names of these people in table form (of course within the foreach I have not organized the data to be displayed in table).

1 answer

3


To combine this data you can create in two-dimensional array:

$dados = array();
foreach($nome as $k => $value){
    $dados[$k]['nome'] = $value;
    $dados[$k]['email'] = $email[$k];
    $dados[$k]['idade'] = $idade[$k];
    $dados[$k]['altura'] = $altura[$k];
}

print_r($dados);

Out

array(
    [0] => array(
        'nome' => 'Guilherme',
        'email' => '[email protected]',
        'idade' => '22',
        'altura' => '1.80',
    )
)
  • Thank you William, your solution was perfect.

Browser other questions tagged

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