str_replace如何在json中值?
How str_replace value in json?
有人可以帮我 json 文件中的 str_replace 值吗?
我的代码在替换字符串上运行良好,但它无法处理 json.
中的值
在所有 json 文件中将 "old" 正确替换为 "new" 效果很好:
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":"1"
替换 "min_order":""
时,它不起作用。我无法直接将 ""
替换为 "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);
}
有人可以帮我解决这个问题吗?
提前谢谢你。
智日
一旦你做了 $file_contents = file_get_contents($path_to_file);
然后您应该使用 json_decode($file_contents);
将 json 字符串转换为数组或对象,
然后通过替换您需要替换的键的值来操纵 array/object,
然后在修改后的数组 json_encode();
上使用将 array/object 转换回 JSON 格式
最后 file_put_contents($path_to_file,$file_contents);
在 json 格式上使用 str_replace 在 JSON 中是可能的,但不可取,也不实用。
有人可以帮我 json 文件中的 str_replace 值吗? 我的代码在替换字符串上运行良好,但它无法处理 json.
中的值在所有 json 文件中将 "old" 正确替换为 "new" 效果很好:
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":"1"
替换 "min_order":""
时,它不起作用。我无法直接将 ""
替换为 "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);
}
有人可以帮我解决这个问题吗?
提前谢谢你。 智日
一旦你做了 $file_contents = file_get_contents($path_to_file);
然后您应该使用 json_decode($file_contents);
将 json 字符串转换为数组或对象,
然后通过替换您需要替换的键的值来操纵 array/object,
然后在修改后的数组 json_encode();
上使用将 array/object 转换回 JSON 格式
最后 file_put_contents($path_to_file,$file_contents);
在 json 格式上使用 str_replace 在 JSON 中是可能的,但不可取,也不实用。