使用PHP从.json文件中删除按ID
我很难通过使用PHP从.json文件中删除按ID,php,json,Php,Json,我很难通过id删除.json文件中的记录。 因此,我的原始JSON如下所示: [["{\"id\":1474753066818,\"name\":\"dd\",\"brand\":\"dd\",\"price\":\"12\"}"],["{\"id\":1474753069035,\"name\":\"dd3\",\"brand\":\"dd\",\"price\":\"12\"}"]] 这是我的php: <?php $string = file_get_contents("p
id
删除.json文件中的记录。
因此,我的原始JSON如下所示:
[["{\"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中那样访问id
,因为整个过程都是一个字符串
我不知道如何将此字符串转换为数组,比较id,然后将其编码回本文开头所示的原始json格式
请帮忙 您的products.json文件有点奇怪,请参见以下内容:
[
[
"{\"id\":1474753066818,\"name\":\"dd\",\"brand\":\"dd\",\"price\":\"12\"}"
],
[
"{\"id\":1474753069035,\"name\":\"dd3\",\"brand\":\"dd\",\"price\":\"12\"}"
]
]
Your products.json包含一个数组数组,其中1个元素的值是json编码的字符串。看起来您必须再次对字符串内容调用json\u 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无效。
[
{"id":1474753066818,"name":"dd","brand":"dd","price":"12"},
{"id":1474753069035,"name":"dd3","brand":"dd","price":"12"}
]