How to show Json fields with PHP

Asked

Viewed 72 times

0

I have the following Json in a PHP variable:

[
   {"pergunta[0]":"Quantos anos?"},
   {"pergunta[1]":"Qual sua altura?"},
   {"resposta[0]":"12"},
   {"resposta[1]":"1.65"}
]

and my goal is to show it as follows:

How old? 12.

How tall are you? 1.65.

I tried that way:

$obj = json_decode([{"pergunta[0]":"Quantos anos?"},{"pergunta[1]":"Qual sua altura?"},{"resposta[0]":"12"},{"resposta[1]":"1.65"}]);
echo $obj['pergunta'];

Any suggestions?

  • Have you tried printar $obj with var_dump() or var_export to understand what structure he has? Look at that

2 answers

0

Your json needs to be serialized (be a string) to make json_decode. For example:

$obj = json_decode('[{"pergunta1":"Quantos anos?"},{"pergunta2":"Qual sua altura?"}]');

echo $obj[0]->pergunta1;

0


$jsonVar = json_decode('{"p0":"Quantos anos?","p1":"Qual sua altura?","r0":"12","r1":"1.65"}');

function mostrar($jsonVar)
{

    foreach ($jsonVar as $key => $value) {

        $pergunta = "none";
        $index = "0";

            if( substr($key, 0, 1) == 'p' )
            {
                $pergunta = $value;
                $index = substr($key, 1, strlen($key) );

                echo  $pergunta . " numero da pergunta:" . $index . " -> ";

                foreach ($jsonVar as $key => $value) {

                    if( $key == 'r'.$index )
                    {
                        echo "Valor da pergunta " .$index. ": " .$value. "
"; } } } } } mostrar($jsonVar);

Upshot:

Quantos anos? numero da pergunta:0 -> Valor da pergunta 0: 12
Qual sua altura? numero da pergunta:1 -> Valor da pergunta 1: 1.65

I hope to help.

Browser other questions tagged

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