[
{
"1":{
"a":"blablabla",
"b":"...",
"c":"..",
"e":"..."
},
"2":{
"a":"blablabla",
"b":"...",
"c":"..",
"e":"..."
},
"3":{
"a":"blablabla",
"b":"...",
"c":"..",
"e":"..."
}
}
]
desired result :
[
{
"1":{
"a":"blablabla",
"b":"...",
"c":"..",
"e":"..."
},
"3":{
"a":"blablabla",
"b":"...",
"c":"..",
"e":"..."
}
}
]
hi,
I have a JSON that looks like this, I would like to be able to delete data 2 for example ( with a b c e ), anyone to help me?
I tried a lot of things but it always ends up deleting everything. I found this which seems to show me the right way, but I can't adapt the code.
$data = file_get_contents('teste_data.json');
$json_arr = json_decode($data, true);
$arr_index = array();
foreach ($json_arr as $key => $value) {
if ($value['YOUR KEY'] == SOME VALUE TO COMPARE) {
$arr_index[] = $key;
}
}
foreach ($arr_index as $i) {
unset($json_arr[$i]);
}
$json_arr = array_values($json_arr);
file_put_contents('teste_data.json', json_encode($json_arr));
I want to retrieve the value deleted with a GET, but then I don't know how to delete only this one
CodePudding user response:
Since you changed your desired result, here is the original answer and the modified one:
Remove the key's in the object:
<?php
$delete = ["a", "c"];
$json = json_decode(file_get_contents('teste_data.json'), true);
foreach ($json[0] as $key => $array) {
foreach ($delete as $value) {
if (array_key_exists($value, $array)) {
unset($array[$value]);
}
}
$json[$key] = $array;
}
file_put_contents('teste_data.json', json_encode(array_values($json)));
Remove the keys in the array:
<?php
$delete = [1, 3];
$json = json_decode(file_get_contents('teste_data.json'), true);
foreach ($delete as $value) {
if (array_key_exists($value, $json[0])) {
unset($json[$value]);
}
}
file_put_contents('teste_data.json', json_encode(array_values($json)));
CodePudding user response:
You have an array level you are not taking into account
Here is the array:
Array
(
[0] => Array (
[1] => Array (
[a] => blablabla
[b] => ...
[c] => ..
[e] => ...
)
[2] => Array (
[a] => blablabla
[b] => hello
[c] => ..
[e] => ...
)
[3] => Array (
[a] => blablabla
[b] => ...
[c] => ..
[e] => ...
)
)
)
So, see comments to find the changes
$data = file_get_contents('teste_data.json');
$json_arr = json_decode($data, true);
$arr_index = array();
foreach ($json_arr[0] as $key => $value) {
// change ^^^
if ($value['b'] == 'SOME VALUE TO COMPARE') {
$arr_index[] = $key;
}
}
foreach ($arr_index as $i) {
unset($json_arr[0][$i]);
// change ^^^
}
$json_arr = array_values($json_arr);
file_put_contents('teste_data.json', json_encode($json_arr));