mardi 9 octobre 2018

Comparing n values in a single array

So I have a associative array that looks like the following:

    3 => {#516
      +"name": "D'Amore Ltd"
      +"id": 67
      +"lon": 40.88
      +"lat": 89.82
      +"catId": 2
      +"locId": 67
      +"distance": 61.538239638491
    }
    4 => {#517
      +"name": "D'Amore Ltd"
      +"id": 67
      +"lon": 40.88
      +"lat": 89.82
      +"catId": 2
      +"locId": 67
      +"distance": 61.538239638491
    }
    5 => {#518
      +"name": "Kuvalis, Denesik and Terry"
      +"id": 14
      +"lon": 41.03
      +"lat": 90.05
      +"catId": 1
      +"locId": 14
      +"distance": 71.218957454573
    }
    6 => {#519
      +"name": "Labadie-Bauch"
      +"id": 1
      +"lon": 40.74
      +"lat": 90.95
      +"catId": 1
      +"locId": 1
      +"distance": 71.523000372967
    }
    7 => {#520
      +"name": "Labadie-Bauch"
      +"id": 1
      +"lon": 40.74
      +"lat": 90.95
      +"catId": 1
      +"locId": 1
      +"distance": 71.523000372967
    }
    8 => {#521
      +"name": "Labadie-Bauch"
      +"id": 1
      +"lon": 40.74
      +"lat": 90.95
      +"catId": 1
      +"locId": 1
      +"distance": 71.523000372967
    }
    9 => {#522
      +"name": "Labadie-Bauch"
      +"id": 1
      +"lon": 40.74
      +"lat": 90.95
      +"catId": 1
      +"locId": 1
      +"distance": 71.523000372967
    }

Now what I am trying to do is iterate through each location and check if the value after it is the same, or the next two values are the same, all the way to the next n values being the same.

So basically if a user passes 4 categories in then it will take the first locations name then check the next 3 locations names and see if they are the same, if so it adds all instances of a location with that name to a collection.

(Note this is faker generated data so the location "Labadie-Bauch" wont have the same catId in all 4 entries the live data)

The following code is my attempt at solving this, which isn't working. I believe this will work for if a user only passes 2 categories but not if they pass n categories.

$final = collect();

dd($locations);
for($i = 0; $i < count($locations);$i++){
    for($j = 1; $j < count($request->categories);$j++){
        if($locations[$i]->name == $locations[$i+$j]->name){
            //add to final collection
        }
    }
}
dd($final);

Aucun commentaire:

Enregistrer un commentaire