Do operations with JSON values - php

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;

Related

Remove space before and after string in array and keep structure

I need to remove all space before string and keep space in string and remove all space after string in array and keep the structure of array
$data = json_decode($json, true);
foreach($data as $index => $value){
$tables = json_encode($value["tables"], JSON_UNESCAPED_UNICODE);
echo $tables;
}
Result from echo $tables;
[{"lang":"cs","lang_title":"Český","menus":[{"header":"Mechanika","rows":[{"parameter":"Hmotnost","value":"0.65kg"}]}]},{"lang":"pl","lang_title":"Polský","menus":[{"header":"Mechanika nová","rows":[{"parameter":"Masa","value":"0.65kg"}]}]},{"lang":"en","lang_title":"Anglický","menus":[{"header":" Me chanics ","rows":[{"parameter":"Weight","value":"0.65kg"}]}]}]
And I need to keep the structure of $value["tables"] and just remove spaces in header,parameter,value
So example "header":" Me chanics " -> "header":"Me chanics"
You can use array_walk_recursive to walk through entire array and use trim to remove extra spaces
$json = '[{"lang":"cs","lang_title":"Český ","menus":[{"header":"Mechanika","rows":[{"parameter":"Hmotnost","value":"0.65kg"}]}]},{"lang":"pl","lang_title":"Polský","menus":[{"header":"Mechanika nová","rows":[{"parameter":"Masa","value":"0.65kg"}]}]},{"lang":"en","lang_title":"Anglický","menus":[{"header":" Me chanics ","rows":[{"parameter":"Weight","value":"0.65kg"}]}]}]';
$data = json_decode($json, true);
array_walk_recursive(
$data, function(&$v, $key) {
if (in_array($key, ["header", "parameter", "value"]))
$v = trim($v);
}
);
echo json_encode($data, JSON_UNESCAPED_UNICODE);
What better you can do is after decoding the data into $data use array_map function
$data = json_decode($json, true);
$data = array_map('trim', $data);
Like this you use instead of foreach.
or either use
trim(); // Function

How to convert specific strings to int from dynamic json's url?

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();

How to edit JSON objects

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
]

How can I get a value from a json string?

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

PHP have decimal numbers with json_encode

I have an issue with some json code where decimal numbers MUST be encoded without quotes and maintain two decimal places
e.g.
{12.34, 33.40, 25.00}
My problem is that the array I have creates the numbers as string
foreach($numbers as $n)
{
$result[] = number_format($n, 2, '.', '');
}
json_encode($result);
// result = {"12.34", "33.40", "25.00"}
You can use floatval():
$result[] = floatval(number_format($n, 2, '.', ''));
I had similar issie with this. This may not be the best code but it work for me. Maybe it can help you.
Try this (I am using codeigniter):
function getData() {
$data = $this->Teplomer_model->showData(); //get your data from database as return $query->result();
//create array
$arr = array();
//foreach data to array
foreach ($data as $row) {
$arr[] = array(
"id" => $row->id_teplota,
"datum" => $row->cas_teplota,
"teplota" => $row->teplota_teplota,
"vlhkost" => $row->vlhkost_teplota
);
}
//echo array as json and check if there is any numbers
echo json_encode($arr, JSON_NUMERIC_CHECK );
}
And output:
{"id":3,"datum":"2019-02-08 14:03:31","teplota":22.33,"vlhkost":19.7},{"id":4,"datum":"2019-02-08 14:18:35","teplota":23,"vlhkost":19}
You could do:
$result[] = (float) number_format($n, 2, '.', '');
Result:
[12.42,33.4,25]
Came across a similar problem. The only way to achieve this is to build the raw json object rather than using json_encode.
$jsonStr = '{';
$lastElement = count($numbers);
$i = 1;
foreach($numbers as $n)
{
$jsonStr .= number_format($n, 2, '.', '');
if($i != $lastElement){
$jsonStr .= ',';
}
$i++;
}
$jsonStr .= '}';
echo $jsonStr;
I know it's not the nicest way to code, but it's the only way to keep decimal points in a json object.

Categories