简体   繁体   中英

json_decode value math's in loop

I have a loop which process a JSON string via json_decode .

I am trying to perform some math calculations on a value before I pass it to my table. At the moment I can echo the desired output inside the loop using echo $mileage1.";"; but I need to change the key lc to the division of 1000 .

There must be a way to do it inside the foreach statement, not in the block: something like foreach(json_decode($url2, true)['status'] ($status["lc"] / 1000) as $status) for example where ($status["lc"] / 1000) does the math outside the loop block.

I haven't been able to find any examples of this specific situation so far. Any suggestions will be greatly appreciated.

Here is a snipplet of my code:

$ret_array = array();
$url2 = file_get_contents("http://URLApi?");
foreach(json_decode($url2, true)['status'] as $status){
//mileage maths??
$mileage = $status["lc"];
$mileage1 = ($mileage) / 1000;
//echo $mileage1.";";
$ret_array[] = $status;
}
return $ret_array;

There are three options to replace the value in the array with the calculated value in a foreach :

First, reference & the value to change it in the original array:

$array = json_decode($url2, true);

foreach($array['status'] as &$status){
    $status["lc"] = $status["lc"] / 1000;
}

Second, modify the original array using the key:

$array = json_decode($url2, true);

foreach($array['status'] as $key => $status){
    $array['status'][$key]["lc"] = $status["lc"] / 1000;
}

Third, create a new result array:

foreach(json_decode($url2, true)['status'] as $status){
    $status["lc"] = $status["lc"] / 1000;
    $result[] = $status;
}

// Or if you need to preserve keys:

foreach(json_decode($url2, true)['status'] as $key => $status){
    $status["lc"] = $status["lc"] / 1000;
    $result[$key] = $status;
}

You could also map each element to a function that does the calculation:

$result = array_map(function($v) { return $v['lc'] = $v['lc'] / 1000; },
                    json_decode($url2, true)['status']);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM