【问题标题】:Remove JSON array index that holds specific value with PHP使用 PHP 删除包含特定值的 JSON 数组索引
【发布时间】:2018-02-13 06:39:00
【问题描述】:

我是 php 的新手。我发现了一些问题,这些问题显示了如何使用 php 从 JSON 文件中删除键/值对,而不是数组索引。

我已经研究出如何使用json_decode() 将值附加到 JSON 文件中的数组。但不是如何删除值。我需要生成一个function() 来寻找c 并删除我的JSON 文件中数组中的任何值。下面是我需要用我的 php 文件生成的预期结果的前后。

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

如果这有助于提供更多上下文,以下是我为向 JSON 中的数组添加值而生成的函数:

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

【问题讨论】:

  • 使用unset(array[index])
  • 使用array_splice()
  • 我已经添加了我用来添加到我的 JSON 文件的函数。这些方法中的任何一种如何适用于此?
  • 您也可以使用array_filter() 删除所有不通过条件的元素。

标签: php arrays json


【解决方案1】:

使用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));
}

这假定数组的所有元素都是空数组或包含客户端名称的 1 元素数组,如您展示的示例中所示。

【讨论】:

  • 谢谢你。数组虽然不是 1 元素。诚然,他们在示例中。也许我可以更清楚。将编辑我的 OP。大概如果我从您的情况中删除 0 这应该解决 1 元素问题?
  • 不行,那么你需要使用array_filter之类的东西来搜索并删除数组中的所有匹配项。
  • 可以是["c", "d"]吗?
  • 它甚至可以是[ ["c", "a", "b"], ["c"], [ ], ["c", "d"], ["d"], ["e"] ],需要变成[ ["a", "b"], [ ], [ ], ["d"], ["d"], ["e"] ]
  • "c" 在该示例中始终排在第一位,但我猜这也不能保证。使用array_filter查看我的答案。
【解决方案2】:

看看array_filterarray_values 函数。

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

根据上面的输入,我假设您正在使用二维数组。然后,您可以使用以下函数来完成这项工作:

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

例子:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-10-25
    • 2022-12-10
    • 2018-10-11
    • 2020-07-05
    • 1970-01-01
    • 2016-03-25
    • 1970-01-01
    • 2015-09-10
    相关资源
    最近更新 更多