Reputation: 51
Hello guys I have a Json file like this.
[
{
"port": 8001,
"password": "test123",
"method": "aes-256-cfb"
},
{
"port": 8002,
"password": "123test",
"method": "aes-256-cfb"
},
{
"port": 8003,
"password": "234test",
"method": "aes-256-cfb"
}
]
I have a variable $q_port
that is 8002, I have to remove from the json file the "port", "password", "method" WHERE "port" = "$q_port"
, this to get a json file like this.
[
{
"port": 8001,
"password": "test123",
"method": "aes-256-cfb"
},
{
"port": 8003,
"password": "234test",
"method": "aes-256-cfb"
}
]
My idea is to do something like this.
$myFile = "01.json";
$q_port = "8002";
$jsondata = file_get_contents($myFile);
$arr_data = json_decode($jsondata, true);
now i dont know how to remove the 3 values
$arr_data = $arr_data = json_decode($arrdata, true);
if(file_put_contents($myFile, $arr_data)) {
echo "Data successfully saved";
}
Do someone know how to remove the 3 values corresponding to the port?
Thank you
Upvotes: 1
Views: 90
Reputation: 92904
With array_filter
function:
...
$q_port = "8002";
$arr = json_decode($jsondata);
$result = array_filter($arr, function($o) use($q_port){
return $o->port != $q_port;
});
file_put_contents($myFile, json_encode(array_values($result)));
Upvotes: 0
Reputation: 79024
Just re-index the array by the port
and unset that key:
$arr_data = array_column($arr_data, null, 'port');
unset($arr_data[$q_port]);
$arr_data
will still be indexed by the port
, so if that is a problem just re-index from 0
:
$arr_data = array_values($arr_data);
NOTE: You might want to leave it indexed by port
and then you don't have to do the above every time.
Then you want to encode not decode:
$arr_data = json_encode($arr_data);
if(file_put_contents($myFile, $arr_data)) {
echo "Data successfully saved";
}
Upvotes: 0
Reputation: 46650
Loop over your array, if the port matches unset it. Then reset the index and json_encode, with pretty print.
<?php
$myFile = "01.json";
$q_port = "8002";
$jsondata = file_get_contents($myFile);
$arr_data = json_decode($jsondata, true);
// loop over each item, if it contains your port, unset it.
foreach ($arr_data as $key => $value) {
if ($value['port'] == $q_port) {
unset($arr_data[$key]);
}
}
// reset the index, prettify back into json
$arr_data = json_encode(array_values($arr_data), JSON_PRETTY_PRINT);
if (file_put_contents($myFile, $arr_data)) {
echo "Data successfully saved";
}
Upvotes: 1