How to display the elements of an array where they are arrays?

Asked

Viewed 686 times

2

I created an array in which each index stores another array - both global so that the values are not deleted. The problem is in displaying each element, when I try, PHP returns me "Notice: Array to string Conversion"

Code:

function cadastrar($nome, $raca, $cor, $tipoPelo){

    $_SESSION['array1'][] = array($nome, $raca, $cor, $tipoPelo);

    $_SESSION['array2'][] = $_SESSION['array1'];


}

function listar(){



    for($i = 0; $i < sizeof($_SESSION['array2']); $i++){
        echo $_SESSION['array2'][$i];
    }

}

With var_dump($_SESSION['array2']); displays:

  Arrayarray(3) { [0]=> array(1) { [0]=> array(4) { [0]=> string(0) "" [1]=> string(0) "" [2]=> string(0) "" [3]=> string(0) "" } } [1]=> array(2) { [0]=> array(4) { [0]=> string(0) "" [1]=> string(0) "" [2]=> string(0) "" [3]=> string(0) "" } [1]=> array(4) { [0]=> string(5) "nome1" [1]=> string(5) "raca1" [2]=> string(4) "cor1" [3]=> string(5) "tipo1" } } [2]=> array(3) { [0]=> array(4) { [0]=> string(0) "" [1]=> string(0) "" [2]=> string(0) "" [3]=> string(0) "" } [1]=> array(4) { [0]=> string(5) "nome1" [1]=> string(5) "raca1" [2]=> string(4) "cor1" [3]=> string(5) "tipo1" } [2]=> array(4) { [0]=> string(5) "nome2" [1]=> string(6) "raça2" [2]=> string(4) "cor2" [3]=> string(5) "tipo2" } } }
  • does so, in the list of a var_dump($_SESSION['array2']) and edit the question with the result.

4 answers

2

From what I understand, you want to store several records in a session. If that’s what you can do something like

function cadastrar($nome, $raca, $cor, $tipoPelo){
    // Verifica se a $_SESSION['dados_cadastro'] existe, caso nao exista, cria um array vazio, caso exista pega o valor e coloca na variabel $dados_cadastro
    $dados_cadastro = isset($_SESSION['dados_cadastro'])?$_SESSION['dados_cadastro']:[];

    // Adiciona no array $dados_cadastro os novos dados enviados
    array_push($dados_cadastro, [$nome, $raca, $cor, $tipoPelo]);

    // Atualiza a $_SESSION['dados_cadastro'] com os dados de todos os cadastros
    $_SESSION['dados_cadastro'] = $dados_cadastro;
}

function listar(){

    // Verifica se a $_SESSION['dados_cadastro'] existe, caso não, informa que nao tem dados
    if(!isset($_SESSION['dados_cadastro'])){
        echo 'Nenhum item cadastrado';
    }else{
        // Faz um loop em todos os dados em $_SESSION['dados_cadastro'] e imprime na tela
        foreach($_SESSION['dados_cadastro'] as $cadastro){
            var_dump('<pre>');
            var_dump($cadastro);
            var_dump('</pre>');
       }
    }
}

We added 3 entries in $_SESSION['dados_register']

cadastrar('nome 1', 'raca 1', 'cor 1', 'tipo_pelo 1');
cadastrar('nome 2', 'raca 2', 'cor 2', 'tipo_pelo 2');
cadastrar('nome 3', 'raca 3', 'cor 3', 'tipo_pelo 3');

When calling list, we will see everything you have in this session variable

listar();

And the way out will be

array(4) {
  [0]=>
  string(6) "nome 1"
  [1]=>
  string(6) "raca 1"
  [2]=>
  string(5) "cor 1"
  [3]=>
  string(11) "tipo_pelo 1"
}
array(4) {
  [0]=>
  string(6) "nome 2"
  [1]=>
  string(6) "raca 2"
  [2]=>
  string(5) "cor 2"
  [3]=>
  string(11) "tipo_pelo 2"
}
array(4) {
  [0]=>
  string(6) "nome 3"
  [1]=>
  string(6) "raca 3"
  [2]=>
  string(5) "cor 3"
  [3]=>
  string(11) "tipo_pelo 3"
}
  • Yes, I want to display the elements of the vector, but in a way that I can manipulate them and without displaying the indexes and other information that is unnecessary to the layman who will access the application.

  • So, inside the loop, you can manipulate the information in any way you want, as in a table, for example. I just gave the dump to show what was stored.

1

There is a repeating structure known for iterating arrays or objects that is the foreach.
Example of how it is used:

$array = Array("maça","banana","uva");
foreach ($array as $elemento) {
    echo $elemento."<br>";
}

Exit:

maça
banana
uva

The first parameter is the array we want to traverse the second is the variable to which the value of an array element will be assigned


To help your problem you can do so:

foreach($array as $elemento){
    if(!is_array($elemento)){
        echo $elemento;
    } else {
        foreach($elemento as $elemento) echo $elemento;
    }
}

It will iterate inside the foreach and check with the is_array if the element is an array, if it is not it will run echo, if it is it will iterate that array.
The tip is to take a look at the PHP documentation, here’s the link to get your doubts about the Foreach

1

This is happening to you because you created an array within an array.

If you remove the [] of $_SESSION['array1'] and $_SESSION['array2'] will work properly.

Example:

function cadastrar($nome, $raca, $cor, $tipoPelo){
    $_SESSION['array1'] = array($nome, $raca, $cor, $tipoPelo);
    $_SESSION['array2'] = $_SESSION['array1'];
}

function listar(){
   cadastrar('teste','teste1','teste2','teste3');
   foreach ($_SESSION['array1'] as $value)
      echo $value . ' ';
}
listar();
  • 1

    I tried here but when removing the brackets the variable only stores the last entered value, I need everything entered to be displayed. So I used an array to save other arrays, they will work as a "database".

  • Unfortunately only displays a group of values. If I add new values the previous ones disappear.

  • Managed to change?

1

Just put another loop inside the first:

foreach($_SESSION['array2'] as $item){
    foreach($item as $subitem){
        echo $subitem;
    }
}

I used the foreach for being simpler, but can do with the for also

  • I tested here but the same error appears.

Browser other questions tagged

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