简体   繁体   English

json_decode值数学在循环中

[英]json_decode value math's in loop

I have a loop which process a JSON string via json_decode . 我有一个循环,通过json_decode处理JSON字符串。

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.";"; 目前,我可以使用echo $mileage1.";";在循环内回显所需的输出echo $mileage1.";"; but I need to change the key lc to the division of 1000 . 但是我需要将密钥lc更改为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. 必须有一种方法可以在foreach语句中而不是在块中进行操作: foreach(json_decode($url2, true)['status'] ($status["lc"] / 1000) as $status)的东西($status["lc"] / 1000)在循环块外进行数学运算的示例。

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 : 有三个选项可将数组中的值替换为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']);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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