如何在PHP中解析此JSON数组?

时间:2013-10-06 00:34:09

标签: php arrays json bitcoin

我一直在玩比特币API,最后让它与我的本地bitcoind服务器进行交互。

现在输入以下代码:

$bitcoin->listreceivedbyaccount();

打印以下内容:

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

)

如何打印或使用[account]或[amount]?

如果有人能帮助我或者至少让我朝着正确的方向前进,我会感激不尽,因为我此刻感到迷茫。

提前致谢。

5 个答案:

答案 0 :(得分:1)

$data = $bitcoin->listreceivedbyaccount();

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

答案 1 :(得分:1)

$arrJSON = $bitcoin->listreceivedbyaccount();
foreach($arrJSON as $arr) {
    print($arr['account']);
    print($arr['amount']);           
}

答案 2 :(得分: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

因此,从这里开始,您可以简单地将它们重新分配为它们自己的变量etc =)

答案 3 :(得分:0)

如果你想使用多个值,这就是一种方式:

$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;
}

答案 4 :(得分: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);