如何在用户个人资料页面显示账户名称?
Hey there! I see you're new to programming and want to show your users' friendly account names (like "savings" or "holidays") instead of the messy raw object or cryptic account IDs on their profile page. Let's get this sorted out step by step.
The Problem with Your Current Code
Right now, this line is causing the confusing output:
<div><h5>Accounts: </h5><?php echo $jData->data->$sUserId->accounts; ?> kr </div>
When you echo a PHP object directly, it just spits out something like Object (or a jumbled string) because PHP doesn't know how to turn that account data into human-readable text automatically. We need to loop through each account and pull out the name property specifically.
The Solution: Loop Through Accounts & Display Names
Replace that problematic accounts section with this code snippet:
<div><h5>Accounts: </h5> <?php // First, make sure the user has accounts to avoid errors if (!empty($jData->data->$sUserId->accounts)) { // Grab the user's accounts object $userAccounts = $jData->data->$sUserId->accounts; // Loop through each account (key = account ID, value = account details) foreach ($userAccounts as $accountId => $accountDetails) { // Output the friendly account name - adjust the HTML to match your page design echo "<p>{$accountDetails->name}</p>"; // Optional: If you want to show the balance alongside the name, uncomment this line // echo "<p>{$accountDetails->name} (Balance: {$accountDetails->balance} kr)</p>"; } } else { // Fallback message if the user has no accounts echo "<p>No accounts found.</p>"; } ?> </div>
What This Does
- Error prevention: The
!empty()check ensures we don't try to loop through non-existent accounts, which would trigger messy errors. - Account iteration: The
foreachloop goes through every account in the user'saccountsobject.$accountIdis the hidden ID (like5c7072a835c3b), and$accountDetailsholds the useful info we want:nameandbalance. - Clean output: We access
$accountDetails->nameto pull the friendly account name and print it in clean, readable HTML.
Bonus Tip for New Developers
To make debugging way easier while you're learning, add these lines right after session_start(); in your PHP file:
error_reporting(E_ALL); ini_set('display_errors', 1);
This will show you clear error messages (like if a property doesn't exist) instead of a blank page or vague system message.
内容的提问来源于stack exchange,提问作者Danko Jimenez

