Search code examples
phpformulaeval

Compute two or more variables in php


I have the following JSON:

 [{
  "units": "06-019",
  "duration_1": "4.96",
  "custom0": "",
  "absolute_mileage_end_0": "31694 km",
  "duration_0": "18.02",
  "duration_stay_0": "7.33",
  "mileage_0": "261 km"
},
{
  "units": "06-021",
  "duration_1": "6.26",
  "custom0": "",
  "absolute_mileage_end_0": "91380 km",
  "duration_0": "21.10",
  "duration_stay_0": "7.66",
  "mileage_0": "603 km"
},
{
  "units": "06-287",
  "duration_1": "10.61",
  "custom0": "",
  "absolute_mileage_end_0": "119741 km",
  "duration_0": "26.67",
  "duration_stay_0": "11.53",
  "mileage_0": "541 km"
},
{
  "units": "06-289",
  "duration_1": "2.44",
  "custom0": "",
  "absolute_mileage_end_0": "89425 km",
  **"duration_0": "7.78",**
  "duration_stay_0": "2.98",
  "mileage_0": "169 km"
}]

I will capture the the following formula

$formula= "duration_0-duration_1";

how can I calculate the result based on the formula for each element in the array in PHP using the eval() function?


Solution

  • Decode the JSON and loop it. Then in the formula, replace the array keys with the values using strtr and eval it:

    $formula = "duration_0-duration_1";
    $array   = json_decode($json, true);
    
    foreach($array as $values) {
        $calc = strtr($formula, $values);
        eval("echo $calc . PHP_EOL;");
        // or
        eval("\$result = $calc;");
    }