How can PHP be used to delete values from a nested JSON structure?

To delete values from a nested JSON structure in PHP, you can recursively traverse the structure and remove the desired values. You can achieve this by using a recursive function that checks each element in the JSON structure and removes the specified values when found.

function deleteNestedValue(&$json, $valueToDelete) {
    foreach ($json as $key => &$value) {
        if (is_array($value)) {
            deleteNestedValue($value, $valueToDelete);
        } else {
            if ($value === $valueToDelete) {
                unset($json[$key]);
            }
        }
    }
}

$json = '{
    "key1": "value1",
    "key2": {
        "nestedKey1": "nestedValue1",
        "nestedKey2": "nestedValue2"
    }
}';

$data = json_decode($json, true);

deleteNestedValue($data, "nestedValue1");

echo json_encode($data, JSON_PRETTY_PRINT);