Answer the question
In order to leave comments, you need to log in
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],
]
[1, 5, 5]
Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question