V
V
Vitaly2017-07-10 19:27:06
PHP
Vitaly, 2017-07-10 19:27:06

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);

The output is:
{"type":"FeatureCollection",
"features":{"1":{"id":2, "properties": {"item": "value"}},"2":{" id":3, "properties": {"item": "value"}}}}
, that is, appends the element's key.
I need the original construct, but without the element
{"type":"FeatureCollection",
"features":[{"id":2, "properties": {"item": "value"}},{"id":3 , "properties": {"item": "value"}}]}
Tell me......
Thanks

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Melkij, 2017-07-10
@melkij

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 question

Ask a Question

731 491 924 answers to any question