Display associative array elements with foreach

1

Hello everyone. I would like to display the elements of an associative array as follows:

Nome: José
Idade: 32
Profissão: Médico

Nome: Rafaela
Idade: 28
Profissão: Dentista

All this on the same page. And the code I'm using is as follows:

<?php
    $usuarios = array(
                    array("nome"=>"José", "idade"=>32, "profissao"=>"Médico"),
                    array("nome"=>"Rafaela", "idade"=>28, "profissao"=>"Dentista"),
                    array("nome"=>"Gabriela", "idade"=>18, "profissao"=>"Não tem")
                );

    foreach ($usuarios as $informacoes => $dados){
        echo $informacoes . " : ";
        echo $dados;
    }
?>

But with this code, I get the following error:

0 : 
Notice: Array to string conversion in /opt/lampp/htdocs/Development/PHP/Exercicio9/usuarios.php on line 10
Array1 : 
Notice: Array to string conversion in /opt/lampp/htdocs/Development/PHP/Exercicio9/usuarios.php on line 10
Array2 : 
Notice: Array to string conversion in /opt/lampp/htdocs/Development/PHP/Exercicio9/usuarios.php on line 10
Array

Searching, I realized that to show the array it would be necessary to give print_r instead of echo , but this command literally shows the array. I would like to know if it is possible and how can I do to display the indexes and their array values in the way I showed.

Thanks in advance.

    
asked by anonymous 05.03.2017 / 07:28

2 answers

2

You can loop inside the other:

 $usuarios = array(
                    array("nome"=>"José", "idade"=>32, "profissao"=>"Médico"),
                    array("nome"=>"Rafaela", "idade"=>28, "profissao"=>"Dentista"),
                    array("nome"=>"Gabriela", "idade"=>18, "profissao"=>"Não tem")
                );
foreach($usuarios as $informacoes) {
  foreach($informacoes as $chave => $valor) {
    echo $chave;
    echo ': ';
    echo $valor;
    echo '<br />';
  }
}
    
05.03.2017 / 21:07
1

You put an associative array inside another assosiative array, try to use this code:

<?php

    header('Content-type: text/html; charset=utf-8');

        $usuarios = array(
                        array("nome"=>"José", "idade"=>32, "profissao"=>"Médico"),
                        array("nome"=>"Rafaela", "idade"=>28, "profissao"=>"Dentista"),
                        array("nome"=>"Gabriela", "idade"=>18, "profissao"=>"Não tem")
                    );

        foreach ($usuarios as $usuario){
            echo "Nome : " . $usuario['nome'] . "<br>";
            echo "Idade :" . $usuario['idade'] . "<br>";
            echo "Profissao :" . $usuario['profissao'] . "<br>";
            echo "<br>";
        }
?>
    
05.03.2017 / 10:20