如何通过用新数据替换旧数据来更新PHP中的JSON数组

时间:2018-09-20 12:26:56

标签: php arrays json replace

我有一个Json文件。在此JSON文件中,我删除了一个对象。我可以通过创建一个新的Array并将此Array写入原始JSON文件来实现。但是在这里,我遇到了一个问题,导致新数据覆盖了整个JSON文件。

我尝试过

array_merge
array_replace
array_merge_recursive
array_replace_recursive

但是我总是得到相同的结果:(在这里我删除了第一个对象)

{
  "server": {
    "SERVER-01": [
        {
            "svc": "SERVICE01",
            "id": 1
        },
        {
            "svc": "SERVICE02",
            "id": 2
        },
        {
            "svc": "SERVICE03",
            "id": 3
        },
        {
            "svc": "SERVICE04",
            "id": 4
        }
    ]
  }
}

原始文件具有以下内容:

{
  "server": {
    "SERVER-01": [
        {
            "svc": "SERVICE01",
            "id": 1
        },
        {
            "svc": "SERVICE02",
            "id": 2
        },
        {
            "svc": "SERVICE03",
            "id": 3
        },
        {
            "svc": "SERVICE04",
            "id": 4
        }
        {
            "svc": "SERVICE05",
            "id": 5
        }
    ]
    "SERVER-02": [
        {
            "svc": "SERVICE01",
            "id": 1
        },
        {
            "svc": "SERVICE02",
            "id": 2
        },
        {
            "svc": "SERVICE03",
            "id": 3
        },
        {
            "svc": "SERVICE04",
            "id": 4
        }
        {
            "svc": "SERVICE05",
            "id": 5
        }
    ]
  }
}

我的问题是,如何在不删除其他阵列的情况下使用新数据更新名为Server-01的阵列?

这是我到目前为止拥有的PHP代码:

// load file
$file = file_get_contents($filename_moni);

// decode copy of json to associative array
$data = json_decode($file, true);

// get ID to delete
$ID = $ID - 1;

unset($data['server'][$Server][$ID]);   

$var=array();
foreach($data['server'][$Server] as $key => $item) {

    $var['server'][$Server][] = $item;      

}

foreach($var['server'][$Server] as $key => $item) {

    if ( $key != $var['server'][$Server][$key]['id'] ) {

        $var['server'][$Server][$key]['svc'] = $item['svc'];
        $var['server'][$Server][$key]['id'] = $key + 1;

    }       

}

$data = array_replace($data,$var);
$jsondata = json_encode($data, JSON_PRETTY_PRINT|JSON_NUMERIC_CHECK);
file_put_contents($filename_moni, $jsondata);

1 个答案:

答案 0 :(得分:0)

对所需的输出没有清晰的描述,似乎您要做的就是用其他/更新的数据替换数组数据...然后这样就足够了:

$arr = json_decode($json, true);

// data items to delete
unset($arr['server']['SERVER-01'][0]['svc']);
unset($arr['server']['SERVER-01'][0]['id']);

// the new (dummy) data that needs to be set in lieu of deleted data
$svc = 'SERVICE09';
$id = 9;

$arr['server']['SERVER-01'][0]['svc'] = $svc;
$arr['server']['SERVER-01'][0]['id'] = $id;

// array with inserted values
echo 'array with newly inserted values';
echo '<pre>';
print_r($arr);
echo '</pre>';