У меня есть JSON файл, который выглядит примерно так:
[
{
"uniqid":"sd54sd54f",
"Make":"Toyota",
"Start Prod":258147369,
"End Prod":369147258
},
{
"uniqid":"6sdf46sd",
"Make":"BMW",
"Start Prod":789456123,
"End Prod":159487263
},
]
Мне нужно удалить всю запись (uniqid, make, start prod и end prod) на основе uniqid, которая будет передана через HTTP-запрос POST. Пока что у меня есть:
$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);
Когда я запускаю код, я не получаю никаких ошибок, но элемент не удаляется...
EDIT: Вот выходная проблема на данный момент. Обратите внимание на нумерацию каждого автомобиля:
{"1":
{
"uniqid":"sd54sd54f",
"make":"Toyota",
"start prod":"258147369",
"end prod":"369147258"
},
"2":
{
"uniqid":"5372ab2109b05",
"make":"6sdf46sd",
"start prod":"789456123",
"end prod":"159487263"},
}
}
Вы упомянули, что будете передавать свой запрос через HTTP POST. В этом случае, чтобы заставить ваш код работать, вы должны изменить $var1 = $_GET['uniqid'];
до $var1 = $_POST['uniqid'];
method="post"
)
Вы можете использовать простую функцию с переменной JSON, переданной по ссылке:
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);
Пример: https://eval.in/150341
Конкретный вариант использования для вас:
$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);
Ну, есть пара ошибок:
Прежде всего, вы должны положить это вверху вашего скрипта:
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 $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');
Это гарантирует, что люди не могут видеть ошибки. Сообщения об ошибках часто включают имена файлов и т.д., Которые не должны видеть люди.
$file = cars.json;
Похоже, JS, а не PHP.file_get_contents()
на нем