Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
172 views
in Technique[技术] by (71.8m points)

php - Changing a string in a json object

I'm trying to update a json file and I'm using laravel command to do it. In that file there are specific product codes that need to be changed. The code I'm doing to do this isn't working, it runs but nothing changes.

Here is my code

$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));

and this is my json file

{
    "P001": {
        "name": "Product 1",
        "price": "200",
        "category": "Shirts"
    },
    "P002": {
        "name": "Product Test",
        "price": "100",
        "category": "Tops"
    },
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Its probably simpler to read the file and create a new JSON with the new codes like this

$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));

RESULT

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...