删除具有相同值的json记录

问题描述 投票:1回答:3

大家好我有这样的Json文件。

[
    {
        "port": 8001,
        "password": "test123",
        "method": "aes-256-cfb"
    },
    {
        "port": 8002,
        "password": "123test",
        "method": "aes-256-cfb"
    },
    {
        "port": 8003,
        "password": "234test",
        "method": "aes-256-cfb"
    }
]

我有一个变量$q_port是8002,我必须从json文件中删除"port", "password", "method" WHERE "port" = "$q_port",这样得到一个像这样的json文件。

[
    {
        "port": 8001,
        "password": "test123",
        "method": "aes-256-cfb"
    },
    {
        "port": 8003,
        "password": "234test",
        "method": "aes-256-cfb"
    }
]

我的想法是做这样的事情。

$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";
        }

有人知道如何删除端口对应的3个值吗?

谢谢

php arrays json
3个回答
1
投票

循环遍历数组,如果端口匹配则取消设置。然后使用漂亮的打印重置索引和json_encode。

<?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";
}

0
投票

只需通过port重新索引数组并取消设置该键:

$arr_data = array_column($arr_data, null, 'port');
unset($arr_data[$q_port]);

$arr_data仍将被port索引,所以如果这是一个问题,只需从0重新索引:

$arr_data = array_values($arr_data);

注意:您可能希望将其保留为port索引,然后您不必每次都执行上述操作。

那么你想编码不解码:

$arr_data = json_encode($arr_data);
if(file_put_contents($myFile, $arr_data)) {
    echo "Data successfully saved";
}

0
投票

使用array_filter功能:

...
$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)));
© www.soinside.com 2019 - 2024. All rights reserved.