首页 > 解决方案 > 更改 json 对象中的字符串

问题描述

我正在尝试更新 json 文件,并且正在使用 laravel 命令来执行此操作。在该文件中有需要更改的特定产品代码。我正在做的代码不起作用,它运行但没有任何变化。

这是我的代码

$old_code = 'P001';
$new_code = 'P011';

$productJson = json_decode(file_get_contents(storage_path('/Product 1/product.json')));

foreach($productJson as $key => $value){
    str_replace($old_code, $new_code, $k);
}

file_put_contents(storage_path('/Product 1/product.json), json_encode($productJson, JSON_PRETTY_PRINT));

这是我的 json 文件

{
    "P001": {
        "name": "Product 1",
        "price": "200",
        "category": "Shirts"
    },
    "P002": {
        "name": "Product Test",
        "price": "100",
        "category": "Tops"
    },
}

标签: phpjsonlaravel

解决方案


读取文件并使用这样的新代码创建新的 JSON 可能更简单

$s = '{"P001": {
  "name": "Product 1",
  "price": "200",
  "category": "Shirts"
},
"P002": {
  "name": "Product Test",
  "price": "100",
  "category": "Tops"
},
"P003": {
  "name": "Product Test",
  "price": "50",
  "category": "Bottoms"
}
}';
 
$old_codes = ['P001', 'P002' ];
$new_codes = ['P011', 'P022' ];

$productJson = json_decode($s);

$new = new stdClass;

foreach($productJson as $key => $json){
    $kk = array_search($key, $old_codes);
    if ( FALSE !== $kk ) { // found
        $new->{$new_codes[$kk]} = $json;
    } else {
        $new->{$key} = $json;
    }
}

echo json_encode($new, JSON_PRETTY_PRINT);

//file_put_contents(storage_path('/Product 1/product.json'), json_encode($new, JSON_PRETTY_PRINT));

结果

{
    "P011": {
        "name": "Product 1",
        "price": "200",
        "category": "Shirts"
    },
    "P022": {
        "name": "Product Test",
        "price": "100",
        "category": "Tops"
    },
    "P003": {
        "name": "Product Test",
        "price": "50",
        "category": "Bottoms"
    }
}

推荐阅读