Danko Jimenez
Danko Jimenez

Reputation: 33

Display JSON on profilepage

How to display the names of accounts on user's profile page? So there would be displayed holidays and savings next to Accounts:

I'm new to coding and I'm trying to display the names of accounts (not the id) that user has and it should be displayed on their profile page. The accounts are saved in clients.json file. Thanks for help!

data/clients.json

{
    "data": {
        "tomas": {
            "name": "eter",
            "accounts": {
                "5c7072a835c3b": {
                    "balance": 1000,
                    "name": "savings"
                },
                "5c7072a835c36": {
                    "balance": 1000,
                    "name": "holidays"
                }
            }
        }
    }
}

my PHP file :

<?php
    session_start();
    if (!isset($_SESSION['sUserId'])) {
        header('Location: login.php');
    }

    $sUserId = $_SESSION['sUserId'];

    $sData = file_get_contents('data/clients.json');
    $jData = json_decode($sData);
    if ($jData == null) {
        echo 'System update';
    }

    $sTotalBalance = array_sum(array_column((array)$jData->data->$sUserId->accounts, 'balance'));

    require_once 'top.php';
?>

<div><h5>Username:</h5> <?php echo $sUserId; ?></div>
<div><h5>Name: </h5><?php echo $jData->data->$sUserId->name; ?></div>
<div><h5>Accounts: </h5><?php echo $jData->data->$sUserId->accounts; ?> kr </div>

<?php
    $sLinkToScript = '<script src="js/profile.js"></script>';
    require_once 'bottom.php';
?>

Upvotes: 3

Views: 79

Answers (1)

Artem
Artem

Reputation: 134

Try iterating it as follows -

foreach($jData->data->$sUserId->accounts as $acc) {
    echo $acc->name;
}

Upvotes: 2

Related Questions