POST variable analysis contains JSON format string PHP
I think you're are definitely on the right track here. I spent a good deal of time trying to refactor, here's what I came up with 

#Validate Function for Json
function jsonDecodeAndValidate($var, $assoc = false) {
    if(!is_string($var))
        return false;
    if(!$decoded = json_decode($var, $assoc))
        return false;
    if(!is_object($decoded) &amp;&amp; !is_array($decoded))
        return false;
    return $decoded;
}
#Parse Function
function buildVirtualData($data) {
    if (is_array($data) || is_object($data)) {
        foreach ($data as $key1 =&gt; $val1) {

            if(is_array($val1)){
                foreach ($val1 as $key2 =&gt; $val2) {
                    $result[$key1][$key2] = buildVirtualData($val2);
                }
            }
            else if($decoded = jsonDecodeAndValidate($val1)){
                $result[$key1] = buildVirtualData($decoded);
            } else {
                if(in_array($val1, ['true', 'false']))
                    $val1 = filter_var($val1, FILTER_VALIDATE_BOOLEAN);
                $result[$key1] = $val1;
            }
        }
        return $result;
    } else {
        if ($decoded = jsonDecodeAndValidate($data, true)) {
            return buildVirtualData($decoded);
        } else {
            return $data;
        }
    }
}


At the very least this will save you some calls to json_decode as the decoding is done once per iteration.

EDIT: I took another stab at it. I think you can boil it down to this.

#decodeand validate
function jsonDecodeAndValidate($var) {
    if(!is_string($var))
        return $var;
    if(!$decoded = json_decode($var, true))
        return $var;
    if(!is_array($decoded))
        return $var;
    return $decoded;
}
#Parse Function
function buildVirtualData($data, &amp;$build) {
    $data = jsonDecodeAndValidate($data);
    if(is_array($data) || is_object($data)){
        foreach($data as $key =&gt; $value){
            buildVirtualData($value, $build[$key]);
        }
    } else {
        if ($data === 'true')
          $data = true;
        if ($data === 'false')
          $data = false;
        $build = $data;
    }
}
# call to Function:
$build = [];
buildVirtualData($_POST, $build);
echo '&lt;pre&gt;';
echo json_encode($build, JSON_PRETTY_PRINT);
echo '&lt;/pre&gt;';


You just have to declare your array outside of the function.