Code Review Stack Exchange is a question and answer site for peer programmer code reviews. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I have a multidimensional array of house properties:

$array = array(
    array('apn' => 345345353, 'sqft' => 1121, 'address' => '12 Lincoln Ave.'),
    array('apn' => 345345351, 'sqft' => 1643, 'address' => '13 Lincoln Ave.'),
    array('apn' => 345345352, 'sqft' => 1222, 'address' => '14 Lincoln Ave.')
    array('apn' => 345345358, 'sqft' => 1226, 'address' => '6 Olark Ave.')
    array('apn' => 345345345, 'sqft' => 1200, 'address' => '323 Pacific Ave.'),
    array('apn' => 345345342, 'sqft' => 1421, 'address' => '324 Pacific Ave.'),
    array('apn' => 345345347, 'sqft' => 1093, 'address' => '328 Pacific Ave.'),
);

What I want to create from it is an array with just the lowest and highest address for each street. If a street has only one address then it shouldn't show up in the array.

array('323 Pacific Ave.', '328 Pacific Ave.', '12 Lincoln Ave.', '14 Lincoln Ave.')

Currently I have the following function that works find but it is very verbose and I'm trying to figure out a simple way to sort by value in a multidimensional array.

function minMaxAddress($data) {
    $addressRanges = array();
    $streets = array();
    $numProperties = count($data);
    $i = 0;
    foreach ($data as $key => $listing) {
        $address = $listing['address'];
        $street = getStreetName($address);
        if ($i == 0) {
          $addressRanges[] = $address;
        }
        else if ($street != end($streets)) {
          $addressRanges[] = $lastAddress;
          $addressRanges[] = $address;
        }
        if ($i == $numProperties - 1) {
            $addressRanges[] = $address;
        }
        $streets[] = $street;
        $lastAddress = $address;
        $i++;
    }
    $addressRanges = array_diff($addressRanges, array_diff_assoc($addressRanges, array_unique($addressRanges)));
    $addressRanges = array_values($addressRanges);
    return $addressRanges;
}
share|improve this question

migrated from stackoverflow.com May 23 '14 at 18:13

This question came from our site for professional and enthusiast programmers.

    
This case is different – Ben Davidow May 21 '14 at 21:54
1  
I can see the need to sort here, but considering that you have to group by street name first there's no need to sort any multidimensional array. Just break up the original into arrays of street numbers and process each one individually. – Jon May 21 '14 at 21:55

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.