I would like to remove "" from a few strings from json which updates every few minutes (http://zergpool.com/api/status).
for example:
{"bitcore":{"name":"bitcore","port":3556,"coins":1,"fees":0,"hashrate":0,"workers":0,"estimate_current":"0.00001745","estimate_last24h":"0.00001756","actual_last24h":"0.00000","hashrate_last24h":105820474.1458},
Fields:
"estimate_current":"0.00001745" -> "estimate_current":0.00001745
"estimate_last24h":"0.00001756" -> "estimate_last24h":0.00001756
"actual_last24h":"0.00000" -> "actual_last24h":0.00000
Since the numbers change all the time, is it possible to write a PHP to convert them in real time? This is what I did.
<?php
$url = 'http://zergpool.com/api/status';
$data = file_get_contents($url);
$manage = json_decode($data,true);
//$aha = (int)preg_replace("/[^\d]+/","",$manage); // tried removing them like this... doesn't work.
echo json_encode($manage)
doesn't work :(
You can use this to remove quotes from numeric values in JSON.
$encoded = json_encode($data, JSON_NUMERIC_CHECK);
Supported in the versions >= PHP 5.3
echo str_replace( '"', '' ,$data);
will remove all the double quotes.
I don't understand why you are trying to remove the double quotes from the $manage line. You can just access the elements of the json that are returned in $manage and convert to float.
$firstString = $manage['bitcore']['estimate_current'];
$firstFloat = (float)$firstString;
var_dump($firstFloat);
or
echo 'floatval=' . floatval($firstString);
Try this:
$json = file_get_contents("https://www.ahashpool.com/api/status/");
$ar = json_decode($json, TRUE);
$filter = [];
foreach ($ar as $k => $sub_ar) {
foreach ($sub_ar as $sub_k => $sub_v) {
if(preg_match('/^[0-9]*\.[0-9]+$/', $sub_v)){
$filter[$k][$sub_k] = (float) $sub_v;
} else {
$filter[$k][$sub_k] = $sub_v;
}
}
}
echo "<pre>";
var_dump($filter);
die();
Related
I am trying to read a string into an array in PHP, but it doesn't work for me.
The string I would like to read:
$output = {"message":"Approved","responseCode":"0","responseCodeDesc":"Transaction Successful"}
The code I am using:
$arr = explode(',', $output);
foreach($arr as $v) {
$valarr = explode(':', $v);
preg_match_all('/"(.*?)"/', $valarr[0], $matches);
$narr[$matches[1][0]][$matches[1][1]] = $valarr[1];
}
Specifically, I would like to access the value for 'message' (i.e., 'Approved').
I tried this, but it still fails:
echo 'MESSAGE ' . $arr['message'];
Here is working code,
$arr = '{"message":"Approved","responseCode":"0","responseCodeDesc":"Transaction Successful"}';
$arr = json_decode($arr, true);
echo $arr['message'];
print_r($arr);
Here is working link
Thats not string, its json..
$array = json_decode($output,true);
I'm on PHP and I need to edit a JSON output to return only objects >=0 and divided by one hundred
Eg.
$json = {"data":[0,55,78,-32,-46,37]}
Needed
$json = {"data":[0,0.55,0.78,0.37]}
How this can be done?
Well, I know this is not the best practice, but if it's as simple as this, you can do the following.
$json = '{"data":[0,55,78,-32,-46,37]}';
// decoding the string to objects & arrays
$x = json_decode($json);
// applying a function on each value of the array
$x->data = array_map(
function($a)
{
if( $a >= 0 ) return $a/100;
else return null;
},
$x->data
);
// Removing empty values of the array
$x->data = array_filter($x->data);
// making a JSON array
$jsonData = json_encode(array_values($x->data));
// inserting a JSON array in a JSON Object
$json = '{"data":' . $jsonData . '}';
// here is your {"data":[0,0.55,0.78,0.37]}
echo $json;
Hope it helps !
Btw, I had to trick the json encode with array_values to prevent the creation of an object rather than an array for the data content. But I guess there is a better method that I just don't know ...
EDIT :
Find out the way :D
Once empty values removed from the array, just do :
$x->data = array_values($x->data);
$json = json_encode($x);
This will do the trick and it will not create issues with the rest of the object.
Alessandro:
Here's my approach, feel free to try. json_decode and a simple foreach can help you...
Code:
$json = array();
$result = array();
$json = '{"data":[0,55,78,-32,-46,37]}';
$decoded_json=json_decode($json, TRUE);
foreach ($decoded_json['data'] as &$value) {
if ($value >= 0){
$value = $value / 100;
$result[]=$value;
}
}
echo json_encode($result);
?>
Result:
[0,
0.55,
0.78,
0.37
]
I have a JSON string in this variable:
$value = $request->pre_departure_type;
With the value:
"30":0 ,"31":2
I want to get the values 30 and 0, 31 and 2 from the above JSON string.
I tried this code:
$result = array();
foreach (explode(',', $value) as $sub) {
$subAry = explode(':', $sub);
$result[$subAry[0]] = $subAry[1];
}
But this didn't explode the string on the double quotes.
If You are getting the perfect answer from your code then i think there is a problem because of double inverted comma. firstly remove it.
$str = str_replace('"', '', $value);
You will get value like below
value = 30:0 ,31:2
after that you will convert it in to array.
First replace double quotes and then do the same process as you did.
$result = array();
$newvalue = str_replace('"', '', $value);
foreach (explode(',', $value) as $sub) {
$subAry = explode(':', $sub);
$result[$subAry[0]] = $subAry[1];
}
If you are getting your desired result but with quotations then simply use this function to remove quotations:
$str = str_replace('"', '', $string_to_replace);
your value coming as a json format so first you need to convert it to object and then array and do manipulation as follow
$valueArr=(array)json_decode($value);
$finalArray=array();
foreach($valueArr as $k=>$v){
array_push($finalArray,$k);
array_push($finalArray,$v);
}
echo "<pre>";print_r($finalArray);
$value = '{"30":0 ,"31":2}'; // this is a json
$data = json_decode($value); // json to object
foreach($data as $key=>$value)
{
echo $key; // get key
echo $value; //get value
}
get values 30 and 0 , 31 and 2 from above
I need to sum all values of "initialContractualPrice" in http://www.base.gov.pt/base2/rest/contratos?&sort(-publicationDate).
I ned to do the operations in php.
who know that can help me?
thank you very much ;)
Try
$data = file_get_contents('http://www.base.gov.pt/base2/rest/contratos?&sort(-publicationDate)');
$data = json_decode($data);
foreach($data as $dat){
echo $dat->publicationDate;
}
You can also use print_r or var_dump to see the structure
This should take care of it.
// Get json from url
$url = 'http://www.base.gov.pt/base2/rest/contratos?&sort(-publicationDate)';
$content = file_get_contents($url);
// Decode json into an array
$json = json_decode($content, true);
// Set default
$total = 0;
// Loop through the array created when decoding json
foreach ($json as $key)
{
// remove symbol from the end leaving only digits
$value = substr(utf8_decode($key['initialContractualPrice']), 0, -1);
// remove the decimal point
$value = str_replace('.', '', $value);
// replace the comma with a decimal point
$value = str_replace(',', '.', $value);
// add this number to the total value
$total += $value;
}
echo $total;
My JSON is encoding peculiarly, so I need to remove every quote before a right-opening bracket. (e.g. every " before a {) Is it possible to do this in PHP, and if so, how?
"{ I would want to remove every occurrence of the quote before the bracket.
JSON here: http://devticker.pw/json-data.php
Code here:
while($row = mysqli_fetch_array($result))
{
$data[] = '{"c": [{ "v": ' . $row['Timestamp'] . '"},{"v":' . $row['USD'] . '} ]}';
}
$str = json_encode(array("rows"=>$data));
$str = substr($str, 1);
$str = str_replace("\"{", "{", $str);
$str = '{"cols":[{"type":"string"},{"type":"number"}],' . $str;
$str = stripslashes($str);
echo $str;
Try
while($row = mysqli_fetch_array($result))
{
$data[] = array("c" => array(array( "v" => $row['Timestamp']), array("v" => $row['USD'] ))));
}
$rows = array("rows"=>$data));
$cols = array("cols" => array(array("type"=>"string"),array("type"=>"number")),$row);
$str = json_encode($cols);
echo $str;
The problem is you are generating part of the JSON manually and then encoding that string with json_encode, which is escaping the quotes that should not be escaped. This is wrong. Using str_replace to remove the escaping is a workarround, not the correct way to generate your JSON.
If you generate your JSON using only json_encode it works well. Something like this should work:
// your columns
$cols = array();
$cols[0] = array('type' => 'string');
$cols[1] = array('type' => 'number');
// your rows
$rows = array();
while ($row = mysqli_fetch_array($result)) {
$r = new stdClass();
$r->c = array();
$r->c[0] = array('v' => $row['Timestamp']);
$r->c[1] = array('v' => $row['USD']);
$rows[] = $r;
}
// the final result
$result = array(
'cols' => $cols,
'rows' => $rows
);
// don't forget this
header('Content-Type: application/json');
echo json_encode($result);
Really can't understand why you need to do this (and why you are manupulating raw JSON string), but you can simply use the string-replacement function of php, str_replace:
$your_json_string = str_replace("\"{", "{", $your_json_string);
What version of PHP are you using?
If 5.3 or greater than you can use this:
return json_encode($var, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT);
Frameworks like drupal have handled this stuff - you could probably rip some code from here to roll your own json_encode function https://api.drupal.org/api/drupal/includes%21common.inc/function/drupal_json_encode/7
$json = str_replace('"{','{',$json)