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

Php 如果精确值匹配,是否从JSON中删除数据?,php,arrays,json,Php,Arrays,Json,这是json被解码的部分 $response = file_get_contents("download.json"); $json = json_decode($response, true); 数据示例 {"count":2948,"errors":"","offers":[{"id":"85305","name":"Some Name", 每个优惠都有自己的名字 数据如下:json->offers->name 如果名称已与其他报价合并,如何删除所有其他报价? 只留下一个名字相同的报价

这是json被解码的部分

$response = file_get_contents("download.json");
$json = json_decode($response, true);
数据示例

{"count":2948,"errors":"","offers":[{"id":"85305","name":"Some Name",
每个优惠都有自己的名字 数据如下:json->offers->name

如果名称已与其他报价合并,如何删除所有其他报价? 只留下一个名字相同的报价

惰性解决方案:

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

假设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++;
    }
}

你能展示一下你为解决这个问题所做的一些尝试吗?我不知道这是如何实现的。你知道如何获得报价列表,对吗?。那么,您将如何访问/检查该数组中的每个项呢?从那里开始。在你开始胡闹之前,先阅读,然后尝试一些东西,如果你的代码有问题就回来。