Processing Multidimensional JSON Array with PHP - php

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 myemail#gmail.com worker. I can access the confirmed_reward, hashrate, ipa, and payout_history, but i'm having trouble 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
}
}
}
Thank you for your help :)

I assume you've decoded the string you gave with json_decode method, like...
$data = json_decode($json_string, TRUE);
To access the stats for the particular worker, just use...
$worker_stats = $data['workers']['myemail#gmail.com'];
To check whether it's alive, for example, you go with...
$is_alive = $worker_stats['alive'];
It's really that simple. )

You can use json_decode to get an associative array from the JSON string.
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']['myemail#gmail.com'] as $stat => $value) {
// Do what you want with the stats
echo "$stat: $value<br>";
}

Why don't you use 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":{"myemail#gmail.com":{"alive":false,"shares":20044,"stales":51}}}');
$aJson['workers']['myemail#gmail.com']; // here's what you want!
?>

$result = json_decode($json, true); // true to return associative arrays
// instead of objects
var_dump($result['workers']['myemail#gmail.com']);

Related

How to create array from object?

I dont know what to call this array-looking object. But When I try to access elements in Php, I cant.
{
"message":"authenticated",
"data": {"id":713,"name":"Jamal","email":"abdurasulovsokhib#gmail.com","role":"user"}
}
I want to access the elements like this. $array['message']=> expecting the outcome to be "authenticated". please help
$JSON = file_get_contents('UserData.json'); // Parsing JSON from file. You can use your own way.
$Array = json_decode($JSON, true); // JSON (string) to Array
echo $Array["message"]; // Output: authenticated
echo $Array["data"]["id"]; // Output: 713

How to read json encoded value using php?

I have a variable in PHP, named as $partialSegments. I want to iterate through it and perform actions when I strike operator or rOperandValue, etc. I receive it in a function call, so while making the
function named(say):
public function convertJsCode($partialSegments){
//logic
}
I am struggling with the logic
"segments":{"type":"custom","partialSegments":[{"type":"7","operator":11,"rOperandValue":["windows xp"],"prevLogicalOperator":null},{"type":"8","operator":11,"rOperandValue":["other"],"prevLogicalOperator":"AND"}]}}
Use json_decode() function in php
<?php
$json = '{"segments":{"type":"custom","partialSegments":[{"type":"7","operator":11,"rOperandValue":["windows xp"],"prevLogicalOperator":null},{"type":"8","operator":11,"rOperandValue":["other"],"prevLogicalOperator":"AND"}]}}';
$parsed = json_decode($json, true);
foreach($parsed["segments"]["partialSegments"] as $val) {
$operator = $val["operator"]; // operator value
$rOperandValue = $val["rOperandValue"][0]; // rOperandValue value
}
?>
Step1: convert json encoded data into php array using json_decode(); function. This function receive two arguments: first one is: json_encoded data which should be decoded and 2nd one is: boolean(TRUE or FALSE). pass second argument as TRUE to convert the json concoded values as php array, if you pass false it will return php object.
Step2: iterate php array and set the logic like a charm.
<?php
$json = '{"segments":{"type":"custom","partialSegments":[{"type":"7","operator":11,"rOperandValue":["windows xp"],"prevLogicalOperator":null},{"type":"8","operator":11,"rOperandValue":["other"],"prevLogicalOperator":"AND"}]}}';
$parsed = json_decode($json, true);
foreach($parsed as $single){
$segments = $single['partialSegments'];
//print_r($single);
foreach($segments as $segment){
echo 'operator:'. $segment['operator'].'<br>';
print_r($segment['rOperandValue']);
// put your logic based on 'operator' or 'rOperandValue'
}
}
?>
Suggestion: Don't use hard code index to work with an array like: $segment['rOperandValue'][0]. array could be empty. i.e: if you want to do anything when a value is found in $segment['rOperandValue'] use in_array().

How to access complex JSON data in PHP

Here is the JSON response in which I need your help.
I need to access "age" key inside 'attribute'.
I really tried every possible ways that i could get. So can u please try to help me out :)
Another option, is that when you call json_decode by default you get a php object, however, if you add an optional boolean parameter you get an array which can be easier in situations like this to access nested elements.
// $data is the original json string
$json = json_decode($data, true);
print_r($json);
There are 2 ways I can see checking the json you just provided, one is by iterating the array, and the other one is accessing it by index:
$json = json_decode($response);
foreach ($json as $item) {
$value = $item->item->attribute->age->value;
var_dump($value);
}
the other way:
$value = $json[0]->item->attribute->age->value;

parsing a json array does not give me the values

below is my 'script.json' file with json array and i want the values of webUserid and webPassword
{
"totalSize":2,
"webUserId":"abc",
"webPassword":"def",
"operation":"send",
"testMode":true,
"records":[
{
"phoneNumber":"1908908399",
"message":"Happy Birthday",
"Id":"a0YL0000008QYunMAG",
"deviceId":"ABCDEFXABCDEF"
}
]
}
I tried below one but not getting the result
<?php
$jsonString=file_get_contents("script.json");
$decoded=json_decode($jsonString,true);
foreach($decoded->data as $name){
echo $name->totalSize;
}
?>
Zarif, try the below code, its working 100%......... :)
<?php
$jsonString=file_get_contents("script.json");
$decoded=array(json_decode($jsonString,true));
foreach($decoded as $name){
echo $name['totalSize'];
}
?>
There's no need for a foreach loop in your current example, as you only have one level.
Your main problem is you're trying to use the result of your json_decode as an object when you've previously stated you want the result as an associative array.
The 2nd param of json_decode specifies what format the return value is in, so as you've done
$decoded = json_decode($jsonString, true);
you'll receive an array, which you could access like
echo $decoded['totalSize'];
if you wanted to treat it as on object as you've done in your question, either state false or omit a 2nd param in json_decode (it's false by default anyway), and that'll let you do what you're trying to do:
$decoded = json_decode($jsonString);
$decoded->totalSize;
lets say that
$myJSON = yourPostedJSON.
$myJSON = json_decode($myJSON, true);
echo $myJSON['webUserId'];
echo $myJSON['webPassword'];

How to loop through this json decoded data in PHP?

I've have this list of products in JSON that needs to be decoded:
"[{"productId":"epIJp9","name":"Product A","amount":"5","identifier":"242"},{"productId":"a93fHL","name":"Product B","amount":"2","identifier":"985"}]"
After I decode it in PHP with json_decode(), I have no idea what kind of structure the output is. I assumed that it would be an array, but after I ask for count() it says its "0". How can I loop through this data so that I get the attributes of each product on the list.
Thanks!
To convert json to an array use
json_decode($json, true);
You can use json_decode() It will convert your json into array.
e.g,
$json_array = json_decode($your_json_data); // convert to object array
$json_array = json_decode($your_json_data, true); // convert to array
Then you can loop array variable like,
foreach($json_array as $json){
echo $json['key']; // you can access your key value like this if result is array
echo $json->key; // you can access your key value like this if result is object
}
Try like following codes:
$json_string = '[{"productId":"epIJp9","name":"Product A","amount":"5","identifier":"242"},{"productId":"a93fHL","name":"Product B","amount":"2","identifier":"985"}]';
$array = json_decode($json_string);
foreach ($array as $value)
{
echo $value->productId; // epIJp9
echo $value->name; // Product A
}
Get Count
echo count($array); // 2
Did you check the manual ?
http://www.php.net/manual/en/function.json-decode.php
Or just find some duplicates ?
How to convert JSON string to array
Use GOOGLE.
json_decode($json, true);
Second parameter. If it is true, it will return array.
You can try the code at php fiddle online, works for me
$list = '[{"productId":"epIJp9","name":"Product A","amount":"5","identifier":"242"},{"productId":"a93fHL","name":"Product B","amount":"2","identifier":"985"}]';
$decoded_list = json_decode($list);
echo count($decoded_list);
print_r($decoded_list);

Categories