-3

This is the part where json gets decoded

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

Example of data

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

Each of the offers has name The data goes like this json->offers->name

How to remove all otheroffers if name has been mached with another offer? And leave only one offer with the same name?

  • 1
    Can you show some attempt that you have made to solve this? – Patrick Q Nov 28 '18 at 14:36
  • I have no idea how this can be accomplished – gaidena Nov 28 '18 at 14:38
  • You know how to get the list (array) of offers, right?. So how would you go about accessing/checking each item in that array? Start there. – Patrick Q Nov 28 '18 at 14:39
  • 1
    before you start bumbling around, read **[this SO post](https://stackoverflow.com/questions/29308898/how-do-i-extract-data-from-json-with-php)**, then try something, and come back if you have issues **with your code**. – YvesLeBorg Nov 28 '18 at 14:42

2 Answers2

0

lazy solution:

    $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;
TsV
  • 629
  • 4
  • 7
0

let's suppose that the json response file has the following values:

$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"}]}';

decode them:

$json = json_decode($response, true);

then remove the repeated offers:

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

by the following recursive function:

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++;
    }
}
Mohammad
  • 3,449
  • 6
  • 48
  • 75