Php Array - Associating data

Asked

Viewed 289 times

0

Hello, I would like to associate the data of chosen in checkbox, with those of an input. I have on one side, a list of results, where I will select in a checkbox, and each one will receive a new value chosen by the user.

For example: On the screen appears Carro1,carro2 and carro3. The user chooses carro1 and carro2, and sets that the carro1 will be called Volks, and the carro2 will be called ford.

then when doing Submit, I will have the following code to perform this operation:

No layout assim:
<input type="checkbox" name="carro[]" />
<input type="text" name="nome_definido_usuario[]" />



E no processamento:
    <?php
        $carro = $_POST['carro'];
        $nome_definido_usuario= $_POST['nome_definido_usuario'];

        $carro_implode = implode("",$carro);
        $nome_definido_usuario_implode = implode("",$nome_definido_usuario);
    ?>

If I echo in $carro_implode and $definido_username_implode, I can visualize the result randomly, as Carro1, Carro2, Volks, Ford. But how do I make the result appear in an associated way, like:
Carro1: Volks
Carro2: Ford

Someone would know?

4 answers

1

To make the association, I think is better this way. Because if some checkbox is not marked, do not lose the index:

<?php
if( $_POST ) {
    foreach( $_POST['carro'] as $key => $value ) {
        echo 'Carro '.$value.': ' . $_POST['nome_definido_usuario'][$value].'<br />';
    }
}
?>

<form method="post">
    <input type="checkbox" name="carro[]" value="1" />
    <input type="text" name="nome_definido_usuario[1]" /> <br />

    <input type="checkbox" name="carro[]" value="2" />
    <input type="text" name="nome_definido_usuario[2]" /> <br />

    <input type="checkbox" name="carro[]" value="3" />
    <input type="text" name="nome_definido_usuario[3]" /> <br />

    <input type="submit" value="Enviar" />
</form>
  • Almost.. The user name is coming empty... as if there was nothing reported in the field by the user..

  • Did you put the number between the brackets? The number that is in the car value[] has to be in the bracket of the username. Type this: name="user_name[2]"

  • I didn’t, because I’m using data from the comic book, with while

1

You can make this association using the function array_combine. This function will return a new associative array from two arrays raised as parameter, where the first will be used as keys and the second as the value of the keys of the first. Emplementando:

<?php
//exemplo de dados submetidos pelo formulario
$_POST['carro'] = ['Carro 1', 'Carro 2'];
$_POST['nome_definido_usuario'] = ['Volks', 'Ford'];

$carros = $_POST['carro'];
$nomes = $_POST['nome_definido_usuario'];

//essa função vai criar um novo array associativo, usando 
//como chave o primeiro e o segundo como os valores de cada chave do primeiro
$carrosNomes = array_combine($carros , $nomes);

//mostrando o conteudo
var_dump($carrosNomes);
echo $carrosNomes['Carro 1'] . '<br>';
echo $carrosNomes['Carro 2'] . '<br>';

//ou de forma mais completa
foreach($carrosNomes as $carro => $nome){
    echo '<br>' . $carro . ': ' . $nome . '<br>';
}

?>

This generates as output:

//saida do var_dump
array(2) { ["Carro 1"]=> string(5) "Volks" ["Carro 2"]=> string(4) "Ford" } 

//acessando chaves do aray $carrosNomes
Volks
Ford

//imprimindo chave e valor de cada elemento do array $carrosNomes
Carro 1: Volks

Carro 2: Ford

Tip: You could merge input with car name and user name into one. Something like:

<input type="checkbox" name="carro[]" value="Volks">
<input type="checkbox" name="carro[]" value="Ford">

Working example

In any file put the code below:

<?php

if(isset($_POST['carro'])){

$carros = $_POST['carro'];
$nomes = $_POST['nome_definido_usuario'];

//essa função vai criar um novo array associativo, usando 
//como chave o primeiro e o segundo como os valores de cada chave do primeiro
$carrosNomes = array_combine($carros , $nomes);

//mostrando o conteudo
var_dump($carrosNomes);
echo $carrosNomes['Carro 1'] . '<br>';
echo $carrosNomes['Carro 2'] . '<br>';

//ou de forma mais completa
foreach($carrosNomes as $carro => $nome){
    echo '<br>' . $carro . ': ' . $nome . '<br>';
}

}
?>

<form method="post">
    <!--É necessario definir um valor para os inputs carro, pis o valor 
    padrão é on, o que pode causar sobrescrita-->
    <input type="checkbox" name="carro[]" value="Carro 1" />
<input type="text" name="nome_definido_usuario[]" />
    <input type="checkbox" name="carro[]" value="Carro 2" />
<input type="text" name="nome_definido_usuario[]" />
    <input type="submit">
</form>

At subter the form the same file will be executed, and the snippet in php will be interpreted, generating the expected output.

Solution to stop joining these two arrays

Just use a little javascript to copy (value) the content from one input to another.

<?php

if(isset($_POST['carro'])){

$carros = $_POST['carro'];

//mostrando o conteudo
var_dump($carros);

//ou de forma mais completa
foreach($carros as $carro => $nome){
    echo '<br>' . $carro . ': ' . $nome . '<br>';
}

}
?>

<form method="post">
    <!--É necessario definir um valor para os inputs carro, pis o valor 
    padrão é on, o que pode causar sobrescrita-->
    <div>
        <input type="checkbox" name="carro[]" value="" class="carros"/>
        <input type="text" name="nome_definido_usuario[]" class="nomes" />
    </div>
    <div>
        <input type="checkbox" name="carro[]" value="" class="carros"/>
        <input type="text" name="nome_definido_usuario[]" class="nomes"/>
    </div>
    <input type="submit">
</form>

<script>
    var nomesDefinidos = document.querySelectorAll('.nomes');

    for (var i = 0; i < nomesDefinidos.length; i++) {
        nomesDefinidos[i].addEventListener('change', function(){
            this.parentElement.querySelector('.carros').value = this.value;
        });
    }
</script>

Basically a class was given for each input (user defined name), added a change event (when something is written in the input and the focus changes), then the input value will be set as input checkbox value.

  • I put it like this: $cars = $_POST['car']; $names = $_POST['username_user']; $carrosNomes = array_combine($cars , $names); foreach($carrosName $car => $name){ echo '<br>' . $car . ': ' . $name . '<br>'; } But no result came.. nothing shows up on the screen. And on the suggestion to join, I believe q would not be ideal, because the idea is to allow the user to modify the names as chosen.

  • and with the var_dump($carrosNomes) appeared bool(false)

  • @Neo I edited the question to put a full and working example. Just put in a file . php and run. Also I put an example where it is not necessary to use two arrays on the server.

  • I need the 2arrays as in the example.. but I put here and continue without getting any results, nothing appears on the screen.

  • @Neo So you are not running correctly, the code of "Working Example", in this link from phpfiddle. The archive code_78149148.php has exactly the content placed in the answer, with the expected output (after filling, of course).

  • The link does not open

  • http://main.xfiddle.com/code_78149148.php ...page not found.. =/

  • =(...someone there?

  • @Neo I think the link has expired. Try this new (in up to 48 hours).

  • I was able to test only today, it has already expired. But within the context I set considering the initial example, I can’t reproduce here. Must be some minor detail..

Show 5 more comments

0

    $carro = $_POST['carro'];
    $nome_definido_usuario= $_POST['nome_definido_usuario'];

    $arrayCarros = array($carro => $nome_definido_usuario);
  • Thus returns only Array

-1

The correct way would be to use an associative array or create an object

<?php
     $carro = $_POST['carro'];
     $nome_definido_usuario= $_POST['nome_definido_usuario'];

     $arrayCarros = array($carro => $nome_definido_usuario);
?>
  • I tried to do something like this: $names2 = array('vw'=>'Volks','FD'=>'Ford','CH'=>'Chevro')..

Browser other questions tagged

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