[英]Deleting from a json file
我有一個看起來像這樣的 json 文件
{
"product_1": {
"category_1": "Category 1",
"category_2": "Category 2"
},
}
我想要做的是當我刪除一個類別時,我想從 json 文件中刪除"key":"value"
。
這是我的代碼
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;
}
發生的情況是,當我刪除一個類別時,它不會將它從 json 中刪除。
我發現奇怪的是,如果我這樣做dd(file_put_contents($storage, json_encode($json, JSON_PRETTY_PRINT)))
然后它會工作但如果我只有file_put_contents($storage, json_encode($json, JSON_PRETTY_PRINT))
然后它不起作用。 所以我不確定我哪里出錯了。
鑒於 $product 和 $category 是鍵,請嘗試此操作:
public function deleteCategory($product, $category)
{
$storage = storage_path("/products.json");
$file = file_get_contents($storage);
$json = json_decode($file, true);
unset($json[$product][$category]);
file_put_contents($storage, json_encode($json, JSON_PRETTY_PRINT));
return (array)$json;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.