John
John

Reputation: 61

PHP parsing JSON with variable key values

I have some json that would like to parse thru without hardcoding the subvalues so others than me can use this as well. Example of the JSON is:

{
"payout_history":"0",
"round_shares":"1816",
"workers":
  {
    "jbo.5970":
      {
        "alive":"1",
        "hashrate":"1253"
      },
    "jbo.5970cpu":
      {
        "alive":"1",
        "hashrate":"21"
      },
    "jbo.5970-2":
      {
        "alive":"1",
        "hashrate":"1062"
      }
  }
}

So those jbo level items I can directly access by ['workers']['jbo.5970'] however tried like ['workers][0] but nothing was returned. Want to parse thru all the items under workers and then process the array elements in each jbo value which could be a completely different named values. Thoughts?

Thanks.

UPDATED INFO:

Using the below, I can get the alive and hash rate status of each worker. But I can not get the name of the worker itself.


    $wemineltc = file_get_contents("http://fakeurl.sincethissite.dontlikelocalhost/wemineltc.json");
    $obj=json_decode($wemineltc,true);
    foreach ($obj['workers'] as $wrk)
        {
          echo $wrk['alive'];
          echo $wrk['hashrate'];
        }

I can also do like $obj['workers']['jbo.5970']['alive'] to get status of a particular worker, however as mentioned I am assuming the workers are dynamic. I basically want to be able to output the name of the worker itself, and then it's alive nad hashrate values. Thoughts?

Here is an example URL by the way: https://www.wemineltc.com/api?api_key=6fd24db2b31d3982ad5520c009588efe81b1b4cc07e9fcd7904d04434405e3ef Thanks.

Upvotes: 0

Views: 1000

Answers (1)

ComFreek
ComFreek

Reputation: 29424

Use a foreach loop:

foreach ($var['workers'] as $jboId => $jboData) {
  var_dump($jboData);
}

Upvotes: 6

Related Questions