Hi I'm using Dreamfactory as REST API backend and I need a PHP script to pre process a POST api request that can modify my received payload from this:
{“Time”:“2018-12-21T07:49:23”,“BME680”:{“Temperature”:20.3,“Humidity”:41.8,“Pressure”:1021.1,“Gas”:286.65}
to this:
{“Time”:“2018-12-21T07:49:23”,“Temperature”:20.3,“Humidity”:41.8,“Pressure”:1021.1,“Gas”:286.65}
How can I acive this with a PHP script ?
First, let's define a helper function which makes the result friendly
function getFriendlyResult(k, input) {
var output = {};
for (var key in input) {
if (key !== k) output[key] = input[key];
}
for (var innerKey in input[k]) output[innerKey] = input[innerKey];
return output;
}
and you can call it like:
getFriendlyResult(“BME680”, {“Time”:“2018-12-21T07:49:23”,“BME680”:{“Temperature”:20.3,“Humidity”:41.8,“Pressure”:1021.1,“Gas”:286.65});
EDIT
To achieve this in PHP, you can call json_decode and pass your JSON, like
$resultArray = json_decode($input, true);
and then implement the same algorithm in PHP as I described above in Javascript.
EDIT
This is an untested implementation in PHP:
function getFriendlyResult($k, $input) {
$output = array();
foreach ($input as $key => $value) {
if ($key !== $k) $output[$key] = $value;
}
foreach ($input[$k] as $innerKey => $innerValue) {
$output[$innerKey] = $innerValue;
}
return $output;
}
$result = json_decode($yourJSON, true);