如果精确值匹配,则从JSON中删除数据?

时间:2018-11-28 14:34:16

标签: php arrays json

这是json解码的部分

$response = file_get_contents("download.json");
$json = json_decode($response, true);

数据示例

{"count":2948,"errors":"","offers":[{"id":"85305","name":"Some Name",

每个offers都有name 数据像这样json->offers->name

如果offers已与其他商品一​​起使用,如何删除所有其他name? 只留下一个同名的报价吗?

2 个答案:

答案 0 :(得分:0)

惰性解决方案:

    $arrayFromJson = (json_decode($json));

    $offers = [];
    $customers = [];
    foreach ($arrayFromJson->toppings as $value) {
            if(in_array($value->name, $customers)){
                continue;
            }
        $offers[] = $value;
        $customers[] = $value->name;
    }

    $arrayFromJson->toppings = $offers;

答案 1 :(得分:0)

让我们假设json响应文件具有以下值:

$response = '{"count":2948,"errors":"","offers":[{"id":"1","name":"a"},{"id":"2","name":"b"},{"id":"3","name":"c"},{"id":"4","name":"a"},{"id":"5","name":"c"},{"id":"4","name":"a"},{"id":"4","name":"a"},{"id":"4","name":"b"}]}';

解码它们:

$json = json_decode($response, true);

然后删除重复的报价:

// make sure that the required index is exists
if(!empty($json['offers'])){
    $json = scan_json_array($json['offers']);
}

通过以下递归函数:

function scan_json_array(array $arr, $index = 0){
    // if we reached the last element of the array, exit!
    if($index == (sizeof($arr)-1)){
        return $arr;
    }

    for(; $index<sizeof($arr);){
        $current = $arr[$index];

        for($j=$index+1; $j<sizeof($arr); $j++){

            $next = $arr[$j];

            if($current['name'] === $next['name']){

                // remove the matched element
                unset($arr[$j]);

                // re-index the array
                $arr = array_values($arr);

                // if it was the last element, increment $index to move forward to the next array element
                if($j == (sizeof($arr)-1)){
                    $index++;   
                }

                return scan_json_array($arr, $index);
            }
        }

        $index++;
    }
}