Answer the question
In order to leave comments, you need to log in
How to remove element from Json array by key?
Greetings!
json file:
{"type":"FeatureCollection",
"features":[{"id":1, "properties": {"item": "value"}},{"id":2, "properties": {"item": "value"}},{"id":3, "properties": {"item": "value"}}]}
Function:
$id = 1;
$file = file_get_contents($_SERVER["DOCUMENT_ROOT"].'/ajax/data.json');
$myArr= json_decode($file,TRUE);
foreach ( $myArr["features"] as $key => $value) {
if (in_array( $id, $value)) {
unset($myArr["features"][$key]);
};
};
$json = json_encode($myArr, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
file_put_contents($_SERVER["DOCUMENT_ROOT"].'/ajax/data.json', $json);
unset($myArr);
Answer the question
In order to leave comments, you need to log in
PHP does not distinguish between a list and an ordered list. The json array cannot have keys. So in an attempt to store array keys, json_encode makes an object with numeric keys. To get a json array, you need to reset the keys of the array, for example:
before calling json_encode
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question