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
Related
How can I remove string . I want to find string that've 2018 then I want to delete string until ,
{"2018-1-8":0,"2018-1-9":0,"2018-1-10":0,"2019-1-1":0,"2019-1-15":0}
How can I display like this
{"2019-1-1":0,"2019-1-15":0}
Note I want to remove "2018-1-8":0,"2018-1-9":0,"2018-1-10":0,
This string is valid JSON which you can parse using json_decode(). You can then modify the data as you want:
// Your string
$json = '{"2018-1-8":0,"2018-1-9":0,"2018-1-10":0,"2019-1-1":0,"2019-1-15":0}';
// Get it as an array
$data = json_decode($json, true);
// Pass by reference
foreach ($data as $key => &$value) {
// Remove if key contains '2018'
if (strpos($key, '2018') !== false) {
unset($data[$key]);
}
}
// Return the updated JSON
echo json_encode($data);
// Output: {"2019-1-1":0,"2019-1-15":0}
Another solution using array_walk():
$data = json_decode($json, true);
array_walk($data, function ($v, $k) use (&$data) {
if (strpos($k, '2018') !== false) { unset($data[$k]); }
});
echo json_encode($data);
// Output: {"2019-1-1":0,"2019-1-15":0}
See also:
passing by reference
strpos()
unset()
json_encode()
Try this maybe :
// Your string
$string = "{\"2018-1-8\":0,\"2018-1-9\":0,\"2018-1-10\":0,\"2019-1-1\":0,\"2019-1-15\":0}";
// Transform it as array
$array = json_decode($string);
// Create a new array
$new_array = array();
// Now loop through your array
foreach ($array as $date => $value) {
// If the first 4 char of your $date is not 2018, then add it in new array
if (substr($date, 0, 4) !== "2018")
$new_array[$date] = $value;
}
// Now transform your new array in your desired output
$new_string = json_encode($new_array);
Output of var_dump($new_string); is {"2019-1-1":0,"2019-1-15":0}
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();
Can any one help me to read this type of json response.
{"\u0000*\u0000_translate":
{
"app_text_newcomer":"Newcomer",
"app_text_senior":"Senior",
"app_text_mostsenior":"Most Senior",
"app_text_results":"Result",
"app_text_result":"Result",
"app_text_agenda":"Agenda",
"app_text_dbvg":"Dbvg"
},
"0":{}
}
how can i get this value \u0000*\u0000_translate
Looks like JSON, so use json_decode to get a PHP object or associative array.
Edit: Having just tried it, I see your problem. json_decode() can't handle nulls in the data, so you should file a bug about that.
Workaround: Preprocess \u0000 to some sentinel value you can later replace for a real null, such as this:
$json = '{"\u0000*\u0000_translate": { "app_text_newcomer":"Newcomer", "app_text_senior":"Senior", "app_text_mostsenior":"Most Senior", "app_text_results":"Result", "app_text_result":"Result", "app_text_agenda":"Agenda", "app_text_dbvg":"Dbvg"}, "0":{}}';
$json = str_replace('\u0000', 'XNULLX', $json);
$arr = json_decode($json, true);
foreach ($arr as $k => $v) {
if (strpos($k, 'XNULLX') !== false) {
unset($arr[$k]);
$k = str_replace('XNULLX', "\0", $k);
$arr[$k] = $v;
}
}
echo var_export($arr, true);
I have json string that I have to edit and then transform back to json. But unfortunately I can't really restore the json structure.
The structure of the original json string ($json):
"[{"Language":{"0":"EN"},"Text":{"0":"xxx"},"ContentType":{"0":"PlainText"}},
{"Language":{"0":"DE"},"Text":{"0":"xxx"},"ContentType":{"0":"PlainText"}},
{"Language":{"0":"FR"},"Text":{"0":"xxx"},"ContentType":{"0":"PlainText"}}]"
The structure I get after my edits ($newJson):
"{"0":{"Language":{"0":"EN"},"Text":{"0":"yyy"},"ContentType":{"0":"PlainText"}},
"1":{"Language":{"0":"DE"},"Text":{"0":"yyy"},"ContentType":{"0":"PlainText"}},
"2":{"Language":{"0":"FR"},"Text":{"0":"yyy"},"ContentType":{"0":"PlainText"}}}"
Here is what I do with my edits:
$jsonArray = object_to_array(json_decode($json));
$editedJsonArray = someLoopStuff($jsonArray);
$newJson = json_encode(array_to_object(($editedJsonArray)));
function object_to_array($obj) {
if(is_object($obj)) $obj = (array) $obj;
if(is_array($obj)) {
$new = array();
foreach($obj as $key => $val) {
$new[$key] = $this->object_to_array($val);
}
}
else $new = $obj;
return $new;
}
function array_to_object($a) {
if (is_array($a) ) {
foreach($a as $k => $v) {
$a[$k] = $this->array_to_object($v);
}
return (object) $a;
}
return $a;
}
Do you have an idea how I could get the same structure as the original json?
Use arrays instead of objects. Pass true to json_decode() as second argument and then do your stuff on arrays.
$jsonArray = json_decode($json, true);
Then just make your operation in loop on $jsonArray and simply use json_encode() without any additional work.
To achieve exactly same output as you have on input you need to cast subarrays on objects:
$jsonArray = json_decode('[{"Language":{"0":"EN"},"Text":{"0":"xxx"},"ContentType":{"0":"PlainText"}},{"Language":{"0":"DE"},"Text":{"0":"xxx"},"ContentType":{"0":"PlainText"}},{"Language":{"0":"FR"},"Text":{"0":"xxx"},"ContentType":{"0":"PlainText"}}]', true);
foreach ($jsonArray as &$item) {
foreach ($item as &$val) {
$val = (object) $val;
}
unset($val);
}
unset($item);
var_dump(json_encode($jsonArray));
Output:
string(226) "[{"Language":{"0":"EN"},"Text":{"0":"xxx"},"ContentType":{"0":"PlainText"}},{"Language":{"0":"DE"},"Text":{"0":"xxx"},"ContentType":{"0":"PlainText"}},{"Language":{"0":"FR"},"Text":{"0":"xxx"},"ContentType":{"0":"PlainText"}}]"
What if you would try to avoid using functions object_to_array and array_to_object. In the encoding part it is not necessary, because json_encode can handle objects or arrays. In the first part json_decode can be called with second optional parameter set to true to produce array instead of object. See PHP manual.
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;