从不同的JSON数组中删除重复项

时间:2019-06-12 13:08:02

标签: arrays json duplicates

我有一个包含很多数组的JSON结构。我想检查是否有重复项。不在同一数组中而是在不同数组中。我还希望其他字段保持原样。

以下是我的结构示例:

T

这是我的期望:

public class B : A
{
    public new void method()
    {
        U u = new U();
        u.method();
    }    
}

我不知道这是否相关,但这是一个Firestore集合。

1 个答案:

答案 0 :(得分:1)

好吧,我不了解Swift,但是我可以向您展示如何做到这一点:

<?php

$json = <<<JSON
{
    "Collection":[
        {
            "field1":[
                "test1",
                "test2",
                "test3"
            ]
        },
        {
            "field2":[
                "test8",
                "test2",
                "test9"
            ]
        }
    ]
}
JSON;

$entities = json_decode($json, true); // Decode JSON

$collection = $entities['Collection']; // Grab array of fields inside collection
$elements = []; // Initialize an empty array of unique elements
$result = [];
foreach ($collection as $index => $fieldObject) {
    $fieldName = array_keys($fieldObject)[0]; // Get field name

    // Get value from array of values of this field
    foreach ($fieldObject[$fieldName] as $valueKey => $value) {

        // Check if your value is not in array of unique elements
        if (!in_array($value, $elements)) {
            $elements[] = $value; // Add value if is not

            // Add value to your new array
            $result['Collection'][$index][$fieldName][] = $fieldObject[$fieldName][$valueKey];
        }
    }
}

$result = json_encode($result); // Encode it back to JSON

这是沙箱中的工作示例:http://sandbox.onlinephpfunctions.com/code/a78cff49cc31c15e7e1373f7e1f66b7951f129e9

相关问题