1

I am a newbie and have an issue in parsing json.

Below is the json array I want to parse:

 array (size=3)
  'status' => string 'success' (length=7)
  'message' => string '' (length=0)
  'data' => 
    array (size=2)
      0 => 
        array (size=2)
          'asset' => string 'ONESATOSHI' (length=10)
          'balance' => string '0.0000001' (length=9)
      1 => 
        array (size=2)
          'asset' => string 'XCP' (length=3)
          'balance' => string '150333.69737005' (length=15)

I want to get the balance of array 1.

I have tried this:

function xcp_balance($wallet)
{   
    $jarr = json_decode(file_get_contents('http://xcp.blockscan.com/api2.aspx?module=address&action=balance&btc_address='.$wallet),true);

    $balance = $jarr['data'][1]['balance'];

    if (is_numeric($balance)) {
        return $balance;
    } else {
        return 0;
    }

}

$wallet = '1NFeBp9s5aQ1iZ26uWyiK2AYUXHxs7bFmB';
xcp_balance($wallet);

But it not working. Kindly help me and apologies for my language.

1 Answer 1

4

Its working. You just forgot to echo the returned value:

function xcp_balance($wallet) {

    $jarr = json_decode(file_get_contents('http://xcp.blockscan.com/api2.aspx?module=address&action=balance&btc_address='.$wallet),true);
    $balance = $jarr['data'][1]['balance'];

    if (is_numeric($balance)) {
        return $balance;
    } else {
        return 0;
    }

}

$wallet = '1NFeBp9s5aQ1iZ26uWyiK2AYUXHxs7bFmB';
echo xcp_balance($wallet); // 150333.69737005
// ^ echo it

Working here

And it might be better to check the existence of that index first:

function xcp_balance($wallet) {

    $jarr = json_decode(file_get_contents('http://xcp.blockscan.com/api2.aspx?module=address&action=balance&btc_address='.$wallet),true);
    $balance = (isset($jarr['data'][1]['balance']) && is_numeric($jarr['data'][1]['balance']) ? $jarr['data'][1]['balance'] : 0);

    return $balance;    
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks alot sir!You have saved me from alot of headache.My Warm Regards to you.
@user2507910 sure no prob. im glad this helped

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.