I
I
Ivan2018-07-19 09:17:31
PHP
Ivan, 2018-07-19 09:17:31

How to find closest value in multidimensional array?

Hello.
I don’t know how exactly to formulate the question correctly, I write it as it is:
Given a multidimensional array of the following form:

[
  [1, 1, 1],
  [1, 2, 1],
  [1, 2, 2],
  [1, 5, 4],
  [1, 5, 6],
  [2, 1, 6],
  [2, 2, 2],
]

An array always consists of arrays of 3 elements and is sorted in ascending order. And given for example the following array: How to find the value in the first array that would be closest (less than or equal) to the second array. For example, for this case it will be the value [1, 5, 4]. I hope the point is clear.
[1, 5, 5]

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Sokolov, 2018-07-19
@asmodeusta

Once sorted, then you just need to go in a row until there is an element that exceeds the given values. Return previous.

function nearest( $sample, $arr) {
  $found = false;
  foreach( $arr AS $row) {
    if($row[0] <= $sample[0]  &&  $row[1] <= $sample[1]  &&  $row[2] <= $sample[2]) $found = $row;
    else break;
  }
  
  return $found;
}

$data = [
  [1, 1, 1],
  [1, 2, 1],
  [1, 2, 2],
  [1, 5, 4],
  [1, 5, 6],
  [2, 1, 6],
  [2, 2, 2],
];

echo implode(',', nearest( [1,5,5], $data)); //  1,5,4

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question