Sep 23, 2020
8
Level 5
Deleting from a json file
I have a json file that looks like this
{
"product_1": {
"category_1": "Category 1",
"category_2": "Category 2"
},
}
What I'm trying to do is when I delete a category I want to remove the "key":"value" from the json file.
Here is my code
public function deleteCategory($product, $category)
{
$storage = storage_path("/products.json");
$file = file_get_contents($storage);
$json = json_decode($file);
unset($json->$product->$category);
file_put_contents($storage, json_encode($json, JSON_PRETTY_PRINT));
return (array)$json;
}
What happens is when I delete a category it doesn't remove it from the json.
And what I found strange was if I did this dd(file_put_contents($storage, json_encode($json, JSON_PRETTY_PRINT))) then it would work but if I only had file_put_contents($storage, json_encode($json, JSON_PRETTY_PRINT)) then it doesn't work. So I'm not sure where I'm going wrong.
Please or to participate in this conversation.