使用PHP处理多维JSON数组

9
这是deepbit.net返回给我比特币矿工的json数据。我想访问workers数组并循环输出myemail@gmail.com矿工的统计信息。我可以访问已确认奖励、哈希速率、ipa和支付历史,但我无法格式化和输出workers数组。
{
 "confirmed_reward":0.11895358,
 "hashrate":236.66666667,
 "ipa":true,
 "payout_history":0.6,
 "workers":
    {
      "myemail@gmail.com":
       {
         "alive":false,
         "shares":20044,
         "stales":51
       }
    }
}

感谢您的帮助 :)
4个回答

21

我假设你已经使用json_decode方法对所提供的字符串进行解码,例如...

$data = json_decode($json_string, TRUE);

要访问特定工作者的统计信息,只需使用...

$worker_stats = $data['workers']['myemail@gmail.com'];

为了检查它是否存活,例如,您可以使用...

$is_alive = $worker_stats['alive'];

就是这么简单。


谢谢,json_decode($json_string, TRUE)解决了问题。第二个参数起了魔法的作用! - Firouziam

4
您可以使用 json_decode 从JSON字符串中获取一个关联数组。
在您的示例中,它可能看起来像这样:
$json = 'get yo JSON';
$array = json_decode($json, true); // The `true` says to parse the JSON into an array,
                                   // instead of an object.
foreach($array['workers']['myemail@gmail.com'] as $stat => $value) {
  // Do what you want with the stats
  echo "$stat: $value<br>";
}

3

为什么不使用 json_decode

你只需要传入字符串,它会返回一个对象/数组,比直接使用字符串更容易操作。

更精确地说:

<?php
$aJson = json_decode('{"confirmed_reward":0.11895358,"hashrate":236.66666667,"ipa":true,"payout_history":0.6,"workers":{"myemail@gmail.com":{"alive":false,"shares":20044,"stales":51}}}');
$aJson['workers']['myemail@gmail.com']; // here's what you want!
?>

2
$result = json_decode($json, true); // true to return associative arrays
                                    // instead of objects

var_dump($result['workers']['myemail@gmail.com']);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接