Processing a multidimensional JSON array using PHP

This is json that returns deepbit.net for my Minic Minco worker. I'm trying to access an array of workers and run a loop to print statistics for my employee myemail@gmail.com. I can access the confirm_reward, hashrate, ipa and payout_history files, but I had problems formatting and outputting the workers array.

{ "confirmed_reward":0.11895358, "hashrate":236.66666667, "ipa":true, "payout_history":0.6, "workers": { " myemail@gmail.com ": { "alive":false, "shares":20044, "stales":51 } } } 

Thanks for the help :)

+6
source share
4 answers

I assume that you have decrypted the string you gave with json_decode , for example ...

 $data = json_decode($json_string, TRUE); 

To access statistics for a specific employee, simply use ...

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

To check if he is alive, for example, you go with ...

 $is_alive = $worker_stats['alive']; 

It's really that simple. )

+15
source

Why don't you use json_decode .

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

More precisely:

 <?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 what you want! ?> 
+3
source
 $result = json_decode($json, true); // true to return associative arrays // instead of objects var_dump($result['workers'][' myemail@gmail.com ']); 
+2
source

You can use json_decode to get an associative array from a JSON string.

In your example, it looks something like this:

 $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>"; } 
+2
source

Source: https://habr.com/ru/post/909481/


All Articles