arrays - Edit & save Json with php -


i'm trying change value in json file. want remove part of string after dot items in 'merchant' key. example, "amazon.com" should replaced "amazon".

here code:

$file = 'myfile.json'; $jsonstring = file_get_contents($file); $data = json_decode($jsonstring, true); foreach ($data $key => $field){     $data[$key]['merchant'] = (explode(".",$data[$key]['merchant'])); } $newjson = json_encode($data); file_put_contents($file, $newjson); 

here json file: (i want replace after .[dot])

[     {         "0": {             "code": "no voucher code",                             "merchant": "amazon.com",                            "title": "upto 70% off on toys, kids apparel , stationary"          },         "1": {             "code": "no voucher code",             "merchant": "ebay.com",                            "title": "set of 3 led bulbs @ rs. 99 + free shipping"                         } 

output: save , replace merchant value

[     {         "0": {             "code": "no voucher code",                             "merchant": "amazon",                            "title": "upto 70% off on toys, kids apparel , stationary"          },         "1": {             "code": "no voucher code",             "merchant": "ebay",                            "title": "set of 3 led bulbs @ rs. 99 + free shipping"                         } 

but code not changing "merchant" values. why not?

use following approach json_decode , strstr functions(i've taken json data string demonstration):

$jsonstring = '[     {         "0": {             "code": "no voucher code",                             "merchant": "amazon.com",                            "title": "upto 70% off on toys, kids apparel , stationary"          },         "1": {             "code": "no voucher code",             "merchant": "ebay.com",                            "title": "set of 3 led bulbs @ rs. 99 + free shipping"                         }     } ]';  $data = json_decode($jsonstring, true);  foreach ($data[0] $key => &$v) {     $v['merchant'] = strstr($v['merchant'], ".", true); } $newjson = json_encode($data, json_pretty_print);  print_r($newjson); 

demo link


Comments

Popular posts from this blog

jOOQ update returning clause with Oracle -

java - Warning equals/hashCode on @Data annotation lombok with inheritance -

java - BasicPathUsageException: Cannot join to attribute of basic type -