我有一个看起来像这样的JSON文件:
[
{
"uniqid":"sd54sd54f",
"Make":"Toyota",
"Start Prod":258147369,
"End Prod":369147258
},
{
"uniqid":"6sdf46sd",
"Make":"BMW",
"Start Prod":789456123,
"End Prod":159487263
},
]
我需要做的是根据将通过HTTP POST请求传入的uniqid删除整个条目(uniqid,make,start prod和end prod)。到目前为止我只有:
$var1 = $_GET['uniqid'];
$file = 'cars.json';
$json = json_decode(file_get_contents($file), true); //im not sure if file_get_contnets is necessary...
$unset_queue = array();
foreach ( $json as $i => $item )
{
if ($item->uniquid == $var1)
{
$unset_queue[] = $i;
}
}
foreach ( $unset_queue as $index )
{
unset($json->json[$index]);
}
$json = array_values($json);
$new_json_string = json_encode($json);
当我运行代码时,我没有错误,但项目未被移除......
编辑:这是此时的输出问题。注意每辆车的编号:
{"1":
{
"uniqid":"sd54sd54f",
"make":"Toyota",
"start prod":"258147369",
"end prod":"369147258"
},
"2":
{
"uniqid":"5372ab2109b05",
"make":"6sdf46sd",
"start prod":"789456123",
"end prod":"159487263"},
}
}
答案 0 :(得分:0)
您已经提到过,您将通过HTTP POST传递您的请求。在这种情况下,为了使您的代码有效,您应该将$var1 = $_GET['uniqid'];
更改为$var1 = $_POST['uniqid'];
答案 1 :(得分:0)
您可以使用带有JSON变量passed by reference的简单函数:
function removeNode($uniqid, &$json) {
$json = json_decode($json, true); // get associative array from json
foreach($json as $key => $each) { // loop through
if($each['uniqid'] == $uniqid) // find matching unique
unset($json[$key]); // remove node from array
}
$json = json_encode($json); // re-encode array as json
}
并像这样使用:
removeNode('6sdf46sd', $json);
特定用例:
$var1 = $_POST['uniqid']; // you're posting the data right?
$file = 'cars.json';
$json = file_get_contents($file);
removeNode($var1, $json);
echo $json; // updated JSON
// or if you want to update the file:
// file_put_contents($file, $json);
答案 2 :(得分:0)
嗯,有几件事是错的:
首先,你应该将它放在脚本的顶部:
error_reporting(-1);
ini_set('display_errors', 'On');
这将显示发生的每一个错误。
其次,你应该修复你的代码。我只是重写并评论了你的代码。向你展示比解释更容易。
// Make sure that you are notified of all errors
error_reporting(-1);
ini_set('display_errors', 'On');
// Get 'uniqid' from POST/GET array; show error if
// it is not set
$var1 = filter_input(INPUT_POST, 'uniqid', FILTER_UNSAFE_RAW);
if ($var1 === null) {
die('The "uniqid" parameter is not set');
}
// Read data from file; show error if it does not work
$data = file_get_contents('cars.json');
if ($data === false) {
die('An error occurred when opening "cars.json"');
}
// Decode JSON; show error if invalid JSON
$json = json_decode($data, true);
if ( ! isset($json[0]['uniqid'])) {
die("The JSON was not decoded correctly");
}
// Go over each item in the array
foreach ($json as $key => $value) {
// If the 'uniqid' equals GET parameter
if ($value['uniqid'] == $var1) {
// Then unset it using the item's $key position
unset($json[$key]);
}
}
// Encode it again
$new_json_string = json_encode($json);
如果是GET请求,则可以使用此代码:
// ...
$var1 = filter_input(INPUT_GET, 'uniqid', FILTER_UNSAFE_RAW);
// ...
当您完成代码并使其生效后,您应该禁用错误:
ini_set('display_errors', 'Off');
确保人们看不到错误。错误消息通常包括文件名等,这不是人们应该看到的。
答案 3 :(得分:-1)
$inputDatabase = array_values(json);