2016-11-16 3 views
-1

Существует массив чисел:Фильтрация массив чисел в соответствии с числовым шаблоном

$list = array 
(
    [0] => 111 
    [1] => 112 
    [2] => 113 
    [3] => 114 
    [4] => 121 
    [5] => 122 
    [6] => 123 
    [7] => 124 
    [8] => 131 
    [9] => 132 
    [10] => 1234 
    [11] => 1123 
    [12] => 1223 
    [13] => 1233 
    [14] => 4321 
) 

и переменный (шаблон):

$input = 1231; 

Я хотел бы, чтобы фильтровать массив следующие правила. Пусть $list[$i] - элемент массива $list, $d - это цифра $list[$i]. Затем

  • , если количество цифр равно $d в $list[$i] больше, чем подсчет цифр, равное $d в $input, то элемент массива должен быть пропущен;
  • если нет $d цифр, указанных в $input, то элемент массива должен быть пропущен.

Например, в вышеупомянутом $input переменной

  • 1 появляется дважды,
  • 2 и 3 появляются один раз.

Тогда все, что появляется больше, чем это должно быть удалено из массива:

$list = array 
(
    [0] => 111 ==> should be removed (1 is only defined twice in $input, so it shouldn't appear more than twice) 
    [1] => 112 
    [2] => 113 
    [3] => 114 ==> should be removed (there is no 4) 
    [4] => 121 
    [5] => 122 ==> should be removed (2 is only defined once, so it shouldn't appear more than once) 
    [6] => 123 
    [7] => 124 ==> should be removed (there is no 4) 
    [8] => 131 
    [9] => 132 
    [10] => 1234 ==> should be removed (there is no 4) 
    [11] => 1123 
    [12] => 1223 ==> should be removed (2 is only defined once in $input, so it shouldn't appear more than once) 
    [13] => 1233 ==> should be removed (3 is only defined once in $input, so it shouldn't appear more than once) 
    [14] => 4321 ==> should be removed (there is no 4) 
) 

Как достичь этого?

+1

почему 111112 .. должны быть удалены? –

+1

вы можете попробовать что-то с [substr_count] (http://php.net/manual/en/function.substr-count.php) и [array_filter] (http://php.net/manual/en/function.array -filter.php) –

+0

Почему в мире '111' следует удалить и' 123' останется? Какова логика этого. Вы должны сказать нам причину не только того результата, который вы хотите. – Irvin

ответ

1
// Prepare counters for the digits in $input 
foreach (str_split((string)$input) as $d) 
    @$counters[$d]++; 

$result = []; 

foreach ($list as $key => $n) { 
    // Counter for digits in $n 
    $tmp_counter = []; 

    foreach (str_split((string)$n) as $d) { 
    // $d is not specified in $input, so skip $n 
    if (empty($counters[$d])) 
     continue 2; 

    // The number of $d entries in $n is greater than 
    // it is specified in $input, so skip $n 
    if (@++$tmp_counter[$d] > $counters[$d]) 
     continue 2; 
    } 

    $result[$key] = $n; 
} 
+0

Вау, это отлично работает !! Большое спасибо! –

-1
For that you can check count of array by splinting and array_unique methode of PHP. 


    $main_arr = array(111,112,113,114,121,122,123,124,131,132,1234,1123,1223,1233,4321); 

    $ans = []; 
    foreach ($main_arr as $value){ 
     $sub_arr = str_split($value); 
     if(count($sub_arr) == count(array_unique($sub_arr))){ 
      array_push($ans,$value); 
     } 
    } 
    print_r($ans); 

This will output: 

Array ( 
[0] => 123 
[1] => 124 
[2] => 132 
[3] => 1234 
[4] => 4321 
) 

Thanks 
+0

OP хочет удалить повторяющиеся числа, которые указаны в переменной '$ input', а не все записи, которые имеют повторяющиеся числа. – jeroen

2

Пожалуйста, дайте мне знать, если он работает

$input = 1123; 
$output = array(111,112,113,114,121,122,123,124,131,132, 1234, 1123, 1223, 1233, 4321); 
$count = count_chars($input, 1); 
$result = array_filter($output, function($n) use($input, $count) { 
    foreach(count_chars($n, 1) as $i => $val) { 
     if(strpos($input, $i) === false) { 
      return 0; 
     }else if($val > $count[$i]){ 
      return 0; 
     } 
    } 
    return 1; 
}); 
+0

Предупреждающее сообщение об ошибке: strpos() ожидает, что параметр 1 будет строкой –

+0

, где объявлен $ input –

+0

Получил это сейчас: Предупреждение Сообщение об ошибке: Недопустимый аргумент, предоставленный foreach() –

Смежные вопросы