【问题标题】:How str_replace value in json?json中的str_replace值如何?
【发布时间】:2020-03-29 12:20:10
【问题描述】:

有人可以帮我解决 json 文件中的 str_replace 值吗? 我的代码在替换字符串上运行良好,但它对 json 中的值不起作用。

在所有 json 文件中正确地将“旧”替换为“新”:

foreach(glob('*.json') as $path_to_file) {
    $file_contents = file_get_contents($path_to_file); 
    $file_contents = str_replace('old','new',$file_contents);
    file_put_contents($path_to_file,$file_contents);
}

但是当我需要将 "min_order":"" 替换为 "min_order":"1" 时,它不起作用。我不能直接用"1" 替换"",因为我在json 中有很多其他值。

我测试了这段代码,但是没有用:

foreach(glob('*.json') as $path_to_file) {
    $file_contents = file_get_contents($path_to_file);
    $file_contents = str_replace('"min_order":""','"min_order":"1"',$file_contents);
    file_put_contents($path_to_file,$file_contents);
}

有人可以帮我解决这个问题吗?

提前谢谢你。 吉日

【问题讨论】:

  • 之前转换为数组。不要尝试编辑 json 字符串!
  • 在 JSON 字符串上使用 str_replace() 会导致各种问题,我原以为这是您最不想做的事情。 "min_order":"" 可能以"min_order" : """min_order": "" 的形式出现,因此它会因各种原因而失败。

标签: php json replace str-replace


【解决方案1】:

一旦你这样做了$file_contents = file_get_contents($path_to_file);

然后您应该使用json_decode($file_contents); 将 json 字符串转换为数组或对象,

然后通过替换你需要替换的键的值来操作数组/对象,

然后在修改后的数组上使用 json_encode(); 将数组/对象转换回 JSON 格式

最后是file_put_contents($path_to_file,$file_contents);

在 JSON 中可以对 json 格式使用 str_replace,但不建议使用,也不实用。

【讨论】:

  • 请注意,如果您不知道要更改的值所在的路径,将json转换为多维数组,然后使用array_walk_recursive搜索值会更方便。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多