DanMad
DanMad

Reputation: 1745

Remove JSON array index that holds specific value with PHP

I am brand new to php.I have found questions that show how to remove key/value pairs from JSON files with php, but not array indexes.

I have worked out how to append values to arrays in a JSON file with json_decode(). But not how to remove values. I need to produce a function() that hunts for c and removes any value within an array in my JSON file. Below is a before and after of the expected outcome I need to produce with my php file.

// before
[["a", "c", "b"], ["c", "c"], [], ["c", "d"], ["d"], ["e"]]
// after
[["a", "b"], [], [], ["d"], ["d"], ["e"]]

Below is the function I have produced in order to add values to arrays in my JSON if this helps provide more context:

function appendClient($file, $post, $client) {
    $a = fopen($file, "r");
    $json = json_decode(fread($a, filesize($file)));
    $json[$post][] = $client;
    fclose($a);
    $a = fopen($file, "w");
    fwrite($a, json_encode($json));
    fclose($a);
}

Upvotes: 0

Views: 175

Answers (2)

Barmar
Barmar

Reputation: 780994

Use array_filter

function removeClient($file, $post, $client) {
    $json = json_decode(file_get_contents($file));
    $json[$post] = array_filter($json[$post], function($x) use($client) {
        return $x != $client;
    });
    file_put_contents($file, json_encode($json));
}

This assumes all the elements of the array are either empty arrays or 1-element arrays containing the client name, as in the example you showed.

Upvotes: 1

Jomoos
Jomoos

Reputation: 13083

Take a look at array_filter and array_values functions.

[["a"],[],["b"],["c"]]

From the above input, I am assuming you are working with 2d array. Then, you can use the following function to do the job:

function removeValues($array, $value) {
    $result = [];

    foreach ($array as $row) {
        $filtered = array_filter($row, function($entry) use($value) {
            return $entry != $value;
        });

        // If you need to reset keys
        $filtered = array_values($filtered);

        $result[] = $filtered;
    }

    return $result;
}

Example:

$input  = [["a"],[],["b"],["c"]];
$output = removeValues($input, "c");
print_r($output);

Upvotes: 0

Related Questions