<?php
function check($string) {
   $result = false;
        if((is_string($string) && (is_object(json_decode($string)) || is_array(json_decode($string))))) {
            $array = json_decode($string);
            $ar = recursion($array);
            $newArr = [];
            foreach($ar as $v){
                $newArr = array_merge($newArr, $v);
            }
            if((recursionValue("foo", $newArr) != false) && (recursionValue("bar", $newArr) != false) && recursionValue("bar", $newArr) == recursionValue("foo", $newArr)){
                $result = true;       
            }  
    }
    return $result;
}
function recursionValue($foo, $array = array()){
    foreach($array as $key => $value){
        if($key == $foo){
            return  $value;
        }
    }
}
function recursion($array, $arrStatic = []){

    static $foo = "foo";
    static $bar = "bar";
    foreach($array as $key => $value){
    if($key == $foo || $key == $bar){
            $arrStatic[] = [$key => $value];  
        }
        if(is_object($value)){
                    $value = (array) $value;
                    $arrStatic = recursion($value, $arrStatic); 
                }   
    }
    return $arrStatic;
}

$str = '{
   "foo": "Test",
   "lastName": "Sidorov",
   "address": {
       "bar": "Test",
       "dem": "God",
       "postalCode": 10001
   },
   "phoneNumbers": [
       "495 111-1234",
       "495 123-7654"
      
   ]
}';

var_dump(check($str));
