Trying to remove a field and value ("ID") from json file: Can anyone please help with this?
JSON:
[{
"Rating": "1600",
"ID": "16733310",
"Name": "LARRATEGUI,MARTIN",
"Expires": "1000.10.10"
},{
"Rating": "1353",
"ID": "16429901",
"Name": "ADDABBO,ERIC M",
"Expires": "1000.10.10"
}]
TRIED THIS:
<?php
$file = file_get_contents("uscf.json");
$file = str_replace('"ID": "[0-9][0-9][0-9][0-9]",','',$file);
$array = json_decode($file, true);
unset ($array.ID);
echo $array;
?>
Desired result
[{
"Rating": "1600",
"Name": "LARRATEGUI,MARTIN",
"Expires": "1000.10.10"
},{
"Rating": "1353",
"Name": "ADDABBO,ERIC M",
"Expires": "1000.10.10"
}]
It's practically always easier to deal with the data after it has been decoded, rather than trying to manipulate the JSON directly.
Decode the JSON from the file, remove the ID
elements from all the arrays, then write the JSON of the updated array back to the file.
$array = json_decode(file_get_contents("uscf.json"), true);
foreach ($array as &$el) {
unset($el['ID']);
}
file_put_contents("uscf.json", json_encode($array));
In the interest of not mutating original data, I'd map the original array to a new one with the ID
keys removed via array_diff_key()
.
$array = json_decode(file_get_contents("uscf.json"), true);
$filter = ['ID' => true]; // only the key is important
$newArray = array_map(function($item) use ($filter) {
return array_diff_key($item, $filter);
}, $array);
Demo ~ https://3v4l.org/3nvtA