Вопрос

I have a php array with zipcodes returned from a db query. Zip Codes are in German format so 5 digit long.

Example:

array ('90475', '90419', '90425', '90415', '90429', '90479', '90485');

I would like to consolidate the values to "ranges" with placeholder, like:

 array ('90...', '904..', '9041.', '9042', '9047.');
 //90485 is left out because there is only 1 match. 

Edit / logic: This is for an autosuggestion search. Trying to build a tree so users can search for entries that match any zipcode starting with 90 or 904, etc.. For the autocomplete to make sense I only want to provide the "9041." value if there is a minimum of two entries matching (90419 and 90415 in example). The zipcodes are always 5 digit long from 00000 - 99999.

Highly appreciate any help. Thanks.

Это было полезно?

Решение 2

$myArray = array ('90475', '90419', '90425', '90415', '90429', '90479', '90485');

$consolidate = array();
foreach($myArray as $zip) {
    for ($c = 2; $c < 5; ++$c) {
        $key = substr($zip, 0, $c) . str_repeat('.',5 - $c);
        $consolidate[$key] = (isset($consolidate[$key])) ? $consolidate[$key] + 1 : 1;
   }
}

$consolidate = array_filter(
    $consolidate,
    function ($value) {
        return $value > 1;
    }
);
var_dump($consolidate);

Другие советы

Here you are:

$length = 5;

$zip = array('90475', '90419', '90425', '90415', '90429', '90479', '90485');

$result = array();

for ($i = 2; $i <= $length - 1; $i++) {
    $pass = array();

    foreach ($zip as $val) {
        $pass[substr($val, 0, $i)]++;
    }

    foreach ($pass as $key => $val) {
        if ($val > 1) {
            $result[] = $key.str_repeat('.', $length - $i);
        }
    }
}

sort($result);

var_dump($result);

This will return in $result an array:

array ('90...', '904..', '9041.', '9042', '9047.');

Every range, which is used only once will be ignored and not returned in $result array.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top