Is there a way to update a JSON Array in PHP by replacing the existing data with the new data?

I am working with a JSON file and have encountered an issue when trying to delete an object. Whenever I create a new array and write it back to the original JSON file, the new data ends up overwriting the entire file.

I have tried using functions like array_merge, array_replace, array_merge_recursive, and array_replace_recursive, but they all result in the same outcome. I always end up with the first object deleted from my JSON structure:

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

The original file contains data for multiple servers, as shown below:

{
  "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
        }
    ]
  }
}

My question is, how can I update the data in a specific server array (e.g., SERVER-01) without removing or affecting the other arrays?

Here is the PHP code that I have been using:

// 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);

Answer №1

If you're looking to update array data without a clear description of the desired output, you can achieve it by following a similar approach like this:

$arr = json_decode($json, true);

// Remove specific data items from the array
unset($arr['server']['SERVER-01'][0]['svc']);
unset($arr['server']['SERVER-01'][0]['id']);

// Define new data to replace the deleted items
$svc = 'SERVICE09';
$id = 9;

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

// Display the updated array values
echo 'Here is the updated array with newly inserted values:';
echo '<pre>';
print_r($arr);
echo '</pre>';

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Could developing a class serve as an effective method for aggregating a set of variables from a JSON object obtained from a graphql API response?

My goal is to extract specific data from a JSON object that comes from a GraphQL API response. I came up with the idea of creating a Python class for the main "parent" object, and then defining each required piece of data as an attribute within that class. ...

No content appearing instead of AngularJS code displayed

My goal is to retrieve data from a MySQL database using PHP and then pass that data in JSON format to AngularJS for display in a table. The HTML code looks like this: <body ng-app="myModule"> <div class="row"> <div class="col-lg-12 ...

Struggling to make json_encode function properly with input from database

Despite my efforts, I can't seem to get json_encode working properly for results retrieved from the fr column in my database. You can find an export of my table at mctrivia.com/language.zip. I have already switched everything to utf8mb4 as recommend ...

Utilizing Pentaho data integration to perform a key-based match for inserting or updating data within a JSON format

My goal is to perform a data Insert / Update operation in a Postgresql database table. The table contains various columns, one of which is a 'details' column of type jsonb where most of my data resides. However, the challenge arises as the key i ...

Encountering challenges while integrating Angular with a Laravel forum creation project

Currently, I am working on building a forum application that involves users, posts, and comments using Laravel. However, the next step in my project requires integrating Angular, which is new territory for me and I'm not sure where to start. I have a ...

When there is no content in the responseText, AJAX will display an error

I've encountered an issue while trying to fetch data using AJAX. The problem lies in receiving an empty responseText. Here's the code I'm working with: JavaScript: function getFounder(id) { var founder = ""; $.ajax({ ...

Looking to display the "loading....." message on a PHP page?

I am working on a PHP webpage where I need to implement the following features: 1. Upon clicking "Say Thanks", it should change to "Done!". 2. Simultaneously, I would like to trigger an action in the indexController. 3. While this action is happening, I wa ...

Serialize custom objects with an array of custom objects using Spring Boot and JSON

Let's take a look at this interesting class structure: @Id @GeneratedValue(strategy=GenerationType.AUTO) private long id; private int key; private String text; private Tag[] tags; private String title; private boolean valid; public Activity(int key, ...

The SELECT statement fails to fetch the most recent data from the database following an INSERT operation

When I make an AJAX request to the same page, my success function in PHP inserts a new record into a table called "some_table" in a MySQL database. Following that, I use jQuery to select data from this table and display it on the page. However, all old rec ...

Struggling to execute JSON parsing with Klaxon and Anko's doAsync?

I am encountering an issue while attempting to parse a JSON-containing URL upon button click: button.setOnClickListener { doAsync{ val result = URL("http://date.jsontest.com/").readText() val parser ...

Guide on accessing public post information through Instagram Graph API using PHP

Seeking guidance on initiating the use of the Graph API to fetch fundamental public details from an Instagram account, such as account name, likes, post date, image URL, and description. While I successfully accomplished this task with the Instagram API, ...

Unexpected behavior when merging objects containing arrays in jq

Struggling to merge multiple objects using jq? If MY_OBJECTS contains JSON objects with a single key each, you can combine them into a single array like this: $ echo ${MY_OBJECTS} | jq -s '.' ... Want to further combine these objects so that al ...

Learn the process of filtering an array using another array

I have a collection of items set up in the following format. items = [ { id: 1, status : "Active" // Other fields tags : [{val: 'IGM', color: 'light-success' }, {val: 'Gated Out', colo ...

How to properly serialize a custom authentication backend in Django

My Django 1.10 application has a custom authentication backend. When I try to log in, the error message TypeError: <class 'CustomAuthBackend'> is not JSON serializable appears. To bypass this issue, I added SESSION_SERIALIZER='django.c ...

verifying for incorrectly formatted object within a JSON list

I'm facing an issue where I need to convert a list of objects into an array. Everything works smoothly when the objects are in good shape, however, it becomes quite challenging to identify which one is malformed when dealing with 4000 records. Is ther ...

Other options instead of employing an iterator for naming variables

I am relatively new to Python, transitioning from a background in Stata, and am encountering some challenges with fundamental Python concepts. Currently, I am developing a small program that utilizes the US Census Bureau API to geocode addresses. My initia ...

combining multiple ajax requests

Thank you for taking the time to review this. Currently, I have a MySQL database that populates a dropdown menu. Upon selection, it fills a second dropdown through an AJAX xmlhttprequest to a PHP file which executes a query on the database. I am now look ...

Best method to conceal PHP errors and save them in the database

Trying to configure a PHP site for production, not development use. The goal is to hide all PHP errors from the user, but log them in a database table instead. However, when changing the defined constants to FALSE, both error display and logging fail: err ...

The issue persists with json_encode as it fails to display the desired JSON output

<?php include("db_connection.php"); if(isset($_POST['id']) && isset($_POST['id']) != "") { // retrieve User ID $user_id = $_POST['id']; // Retrieve User Details from database $query = "SELECT * FROM prod ...

Changing the locale in Silverstripe with the fluent module

Good day, I am curious if anyone is aware of a way to manually set the locale. I need to update some items in the database based on the locale using a cronjob, but instead of using the server's locale, I want to set it based on certain variables. Is ...