kodie
9/21/2017 - 6:34 PM

Sort a multidimensional array by value closest to a number

<?php
function sortByClosest(array $arr, string $key, $num) {
  $closest = array();
	
  foreach ($arr as $akey => $aval) {
    $closest[$akey] = abs($aval[$key] - $num);
  }
	
  asort($closest);

  return array_merge($closest, $arr);
}

$listings = array(
  "prop1" => array(
    "zipcode" => "50317"
  ),
  "prop2" => array(
    "zipcode" => "50316"
  ),
  "prop3" => array(
    "zipcode" => "50314"
  ),
  "prop4" => array(
    "zipcode" => "50318"
  ),
  "prop5" => array(
    "zipcode" => "50320"	
  )
);

$listings = sortByClosest($listings, 'zipcode', 50317);

print_r($listings);
?>