Last active
May 25, 2017 13:00
-
-
Save calexandrepcjr/9ceac0332783f521aa09241e86ecc72a to your computer and use it in GitHub Desktop.
A helper to play with arrays
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/*EXAMPLE | |
$array = array( | |
0 => array ( | |
0 => 35, | |
1 => 30, | |
2 => 39 | |
), | |
1 => array ( | |
0 => 20, | |
1 => 12, | |
2 => 5 | |
), | |
); | |
$user = array(19,13,3);*/ | |
//END EXAMPLE | |
//Calculates which dimension of an array is closer of user's input | |
function array_proximity($referencial, $input){ | |
$totalRef = count($referencial); | |
if (is_array($referencial)){ | |
for ($i = 0; $i < $totalRef; $i++) { | |
if (is_array($referencial[$i])){ | |
$totalSubRef = count($referencial[$i]); | |
$proximity = array(); | |
for ($j = 0; $j < $totalSubRef; $j++) { | |
$proximity[$i] += abs($referencial[$i][$j] - $input[$j]); | |
} | |
if ($i > 0){ | |
if ($maxProximity['distance'] > $proximity[$i]) { | |
$maxProximity['distance'] = $proximity[$i]; | |
$maxProximity['index'] = $i; | |
} | |
} else { | |
$maxProximity['distance'] = $proximity[$i]; | |
$maxProximity['index'] = $i; | |
} | |
} | |
} | |
return $maxProximity; | |
} else { | |
exit('Unexpected referencial. Must be an array.'); | |
} | |
} | |
//EXAMPLE | |
//$found = find($array, $user); | |
//print_r($found); | |
//END EXAMPLE | |
//RESULTS Array ( [distance] => 4 [index] => 1 ) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment