使用PHP从.json文件中删除ID
问题描述:
我很难通过id
删除我的.json文件中的记录。 所以我原来的JSON看起来是这样的:使用PHP从.json文件中删除ID
[["{\"id\":1474753066818,\"name\":\"dd\",\"brand\":\"dd\",\"price\":\"12\"}"],["{\"id\":1474753069035,\"name\":\"dd3\",\"brand\":\"dd\",\"price\":\"12\"}"]]
这是我的PHP:
<?php
$string = file_get_contents("products.json");
//var_dump($string);
$input = json_decode($string, true);
$output = array();
//here starts the problem
foreach($input as $element) {
if($_GET['data'] != $element[0]["id"]){ //add in array if id doesn't match
$output[] = $element;
}
}
$final = json_encode($output);
$f = @fopen("products.json", "r+");
if ($f !== false) {
ftruncate($f, 0);
fclose($f);
}
file_put_contents("products.json", $final);
>
基本上我的问题在foreach
开始的地方,我通过一些看起来像这样的迭代:
array(2) { [0]=> array(1) { [0]=> string(58) "{"id":1474753066818,"name":"dd","brand":"dd","price":"12"}" } [1]=> array(1) { [0]=> string(59) "{"id":1474753069035,"name":"dd3","brand":"dd","price":"12"}" } }
很明显,在这里我无法访问id
就像我正在尝试做的那样,因为整件事是一个字符串。
我不知道如何将这个字符串转换为一个数组,然后比较该id,然后将其编码回本文开头显示的原始json格式。
请帮忙!
答
你products.json文件是有些奇怪,见下文:
[
[
"{\"id\":1474753066818,\"name\":\"dd\",\"brand\":\"dd\",\"price\":\"12\"}"
],
[
"{\"id\":1474753069035,\"name\":\"dd3\",\"brand\":\"dd\",\"price\":\"12\"}"
]
]
你products.json包含数组的数组具有1个元件,其值是编码的字符串一个JSON。看起来你必须再次调用字符串内容json_decode
才能得到你想要的内容。
foreach($input as $element) {
$product = json_decode($element[0]);
if($_GET['data'] != $product["id"]){
//add in array if id doesn't match
$output[] = $product ;
}
}
同样重要的是要注意,你的代码的其余部分:
$final = json_encode($output);
$f = @fopen("products.json", "r+");
if ($f !== false) {
ftruncate($f, 0);
fclose($f);
}
file_put_contents("products.json", $final);
不会结束了节省您当前正在阅读它以同样的方式products.json。使用上面提供的代码,它可能会看起来像这样:
[
{"id":1474753066818,"name":"dd","brand":"dd","price":"12"},
{"id":1474753069035,"name":"dd3","brand":"dd","price":"12"}
]
您的JSON无效。 –