Print json in php with titles?

Asked

Viewed 55 times

-1

<?php
$dadosJsonDecodificados = ("C:/pasta/arquivojson.json");
foreach($dadosJsonDecodificados->accountData $dadosBank){
   $msg = ($dadosBank->accountBalance);
}
$str = implode("\n", $msg);
echo ($str);

?>

Inside the Json Example :

    "accountData": [
    {
        "AccountName" :"Bruno",
        "accountBalance": [
                1000,
                2000,
                3000
              ]
    }
    ]

Result = String:
1000
2000
3000

and if I want to print on the screen like this :
Quantity 1: 1000
Quantity 2: 2000
Quantity 3: 3000
someone could give me an example ? I’m picking up a json file that generates automatically !

1 answer

-1


Opa Runo, then, to do this you need to use the function json_decode. But your code is half incomplete, because for you to get the content of this json would be through a file_get_contents for example.

$json = '{
   "accountData": 
      [
        {
            "AccountName" :"Bruno",
            "accountBalance": [
                1000,
                2000,
                3000
            ]
        },
        {
            "AccountName" :"Matheus",
            "accountBalance": [
                1500,
                2700,
                3090
            ]
        }
     ]
}'; // no seu caso seria o arquivo!!

Note that I added keys at the beginning of your json to the example

$obj = json_decode($json); // converte o json para um objeto

foreach($obj->accountData as $account) { // percorre cada account
    echo "AccountName: {$account->AccountName}\n";
    
    $i = 0; // contador para o balance
    foreach($account->accountBalance as $balance) { // percorre cada accountBalance
        $i++;
        echo "Quantidade {$i}: {$balance}\n";
    }
    
    echo "-------------\n";
}

That’s right aew, I hope I helped!!

Browser other questions tagged

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