Skip to content
Advertisement

Cluster PHP array

Let’s say I have an array of items with each item a value. I’d like to create a new array where the items are clustered by their relative distance to each other. When an item has a distance of one to another item, they belong to each other.

JavaScript

This will create an output of overlapping arrays. What I want is that, because item-a and item-b are related, and item-b is also related to item-c, I’d like to group item-a, item-b, and item-c to each other. The distance to item-c and item-d is greater than 1 so it will for a cluster of itself.

JavaScript

How do I even start coding this?

Thanks in advance and have a nice day!

Advertisement

Answer

This can only be tested in your environment but here is what it does

  • it attempts to find relative distances based on array index 0’s hash
  • it resorts the input array by distances (assuming that in this stage some will be positive and some negative) – that gives us the info to put the hash array in an order
  • Take this new array and put the hash back in
  • build a final output array measuring distances and sorting the level of output array by a threshhold.

I put in a couple dummy functions to return distances, obviously replace with your own. This might need tweaking but at this point, it’s in your hands.

JavaScript
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement