首页 > 解决方案 > 未定义的属性:stdClass::$category

问题描述

我有一个看起来像这样的 json 文件

{
    "Product_1": {
        "name": "Product 1",
        "category": "Yellow"
    },
    "Product_2": {
        "name": "Product 2",
        "category": "Blue"
    },
    "Product_3": {
        "name": "Product 3",
        "category": "Yellow"
    }
}

如果该类别是黄色的,我需要对我的所有类别进行批量更改。当我尝试这样做时,我收到此错误

Undefined property: stdClass::$category

这是我的代码

$products = Product::all();

foreach($products as $product)
{
    $json = file_get_contents(storage_path("products/$product->id/products.json"));
    $productJson = json_decode($json);

    if($productJson->category == 'Yellow')
    {
        $productJson->category = 'Green';
        file_put_contents(storage_path("products/$product->id/products.json"), json_encode($productJson, JSON_PRETTY_PRINT));
    }
}

当我得到这个dd($productJson)

{
  +"name": "Product 1"
  +"category": "Yellow"
}

如果我var_dump($productJson)得到我的 json 输出,但之后我也会得到错误。

标签: phplaravellaravel-7

解决方案


推荐阅读