2013-10-06 38 views
0

我一直在玩比特幣API,最後讓它與我的本地bitcoind服務器進行交互。如何解析PHP中的這個JSON數組?

現在下面的代碼:

$bitcoin->listreceivedbyaccount(); 

打印如下:

Array 
(
    [0] => Array 
     (
      [account] => root213 
      [amount] => 1 
      [confirmations] => 3 
     ) 

) 

如何打印或[帳戶]或[金額]例如工作?

如果有人能幫助我,或者至少讓我走向正確的方向,我會很感激,因爲我現在感到迷茫。

在此先感謝。

+2

如果你不知道如何使用數組,我認爲你應該在製作程序之前閱讀教程。 – Oriol

回答

0
/** 
* Firstly collect the data 
* as an accessible variable 
**/ 
$SomeVar = $bitcoin->listreceivedbyaccount(); 

/** 
* Print the contents for just demonstration! 
* (Dont use print_r() in production!) 
**/ 
print_r($SomeVar); 
Array 
(
    [0] => Array 
     (
      [account] => root213 
      [amount] => 1 
      [confirmations] => 3 
     ) 

) 

進入 '帳戶'

echo $SomeVar[0]["account"]; //echos root213 

訪問 '金額'

echo $SomeVar[0]["amount"]; //echos 1 

因此,從現在起,你可以簡單地再重新分配這些作爲自己的變量等等=)

+0

現在我覺得非常愚蠢,但我感謝你。所以這只是一個層次類型的東西? – Dutchiavelli

+0

Yea =)雖然,顯然樹木變得更深,你需要通過循環訪問它們,不用擔心,我們都從某處開始!還有什麼我可以幫忙的嗎? – MackieeE

+0

不好意思,當我發佈這個消息時,我面臨着自己的問題,因爲它基本上是我用SQL查詢所做的事情:echo $ row ['name'];等等 – Dutchiavelli

1
$data = $bitcoin->listreceivedbyaccount(); 

$account = $data[0]['account']; 
$amount = $data[0]['amount']; 
0

這裏有一種方法,如果你wa NT與多個值工作:

$data = $bitcoin->listreceivedbyaccount(); 
$count = count($data); 
// Avoid errors 
$amounts = array(); 
// Avoid errors 
$confirmations = array(); 
for ($i = 0; $i < $count; $i++) { 
    $amounts[] = $data[$i]['amount']; 
    $confirmations[] = $data[$i]['confirmations']; 
} 
foreach ($amounts as $amount) { 
    // Do something, like: 
    // print $amount; 
} 
1
$arrJSON = $bitcoin->listreceivedbyaccount(); 
foreach($arrJSON as $arr) { 
    print($arr['account']); 
    print($arr['amount']);   
} 
0

這裏的另一種選擇我用所有的時間,將非數組的數組:

/** 
* Convert a string, number, or object into an array. 
* Especially useful for objects such as those that 
* come from simplexml_load_file(), etc. 
* 
* @param mixed $non_array 
* Any string, number, or object. 
* 
* @return 
* An "arrayified" version of $non_array. At minimum, 
* this should always return an empty array. 
*/ 
function arrayify($non_array) { 
    if (empty($non_array) && $non_array !== 0) { 
    return array(); 
    } 
    return unserialize(serialize(json_decode(json_encode((array) $non_array), 1))); 
} 

然後使用這樣的提取JSON數據:

$data = arrayify($bitcoin->listreceivedbyaccount()); 
print_r($data);