用 PHP 处理多维 JSON 数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9471592/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 06:53:39  来源:igfitidea点击:

Processing Multidimensional JSON Array with PHP

phpjson

提问by 0xDECAFBAD

This is the json that deepbit.net returns for my Bitcoin Miner worker. I'm trying to access the workers array and loop through to print the stats for my [email protected] worker. I can access the confirmed_reward, hashrate, ipa, and payout_history, but i'm having trouble formatting and outputting the workers array.

这是 deepbit.net 为我的 Bitcoin Miner 工人返回的 json。我正在尝试访问工作人员数组并循环打印 [email protected] 工作人员的统计信息。我可以访问confirmed_reward、hashrate、ipa 和payout_history,但是我在格式化和输出workers 数组时遇到问题。

{
 "confirmed_reward":0.11895358,
 "hashrate":236.66666667,
 "ipa":true,
 "payout_history":0.6,
 "workers":
    {
      "[email protected]":
       {
         "alive":false,
         "shares":20044,
         "stales":51
       }
    }
}

Thank you for your help :)

感谢您的帮助 :)

回答by raina77ow

I assume you've decoded the string you gave with json_decodemethod, like...

我假设你已经解码了你用json_decode方法给出的字符串,比如......

$data = json_decode($json_string, TRUE);

To access the stats for the particular worker, just use...

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

$worker_stats = $data['workers']['[email protected]'];

To check whether it's alive, for example, you go with...

例如,要检查它是否还活着,您可以使用...

$is_alive = $worker_stats['alive'];

It's really that simple. )

真的就是这么简单。)

回答by Cyril N.

Why don't you use json_decode.

你为什么不使用json_decode

You pass the string and it returns an object/array that you will use easily than the string directly.

您传递字符串并返回一个对象/数组,您将比直接使用字符串更容易使用。

To be more precise :

更准确地说:

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

回答by connec

You can use json_decodeto get an associative array from the JSON string.

您可以使用json_decode从 JSON 字符串中获取关联数组。

In your example it would look something like:

在您的示例中,它看起来像:

$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']['[email protected]'] as $stat => $value) {
  // Do what you want with the stats
  echo "$stat: $value<br>";
}

回答by AndreKR

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

var_dump($result['workers']['[email protected]']);