2017-09-04 119 views
1

我有這個數組[1,1,2,2,2,3,4,4,5,6,6,6,7],我可以根據範圍值對數組進行分組,所以得到的最終結果:組數組按範圍值

'1-3' = [1,1,2,2,2,3]; // Count is 6 '4-5' = [4,4,5]; // Count is 3 '6-7' = [6,6,6,7]; // Count is 4

+1

是的,可以。如何定義範圍?他們可以改變嗎?你期望的結果是什麼?你想數數還是組?這個問題有點含糊。 – salathe

+0

嘿@salathe,對不起我的英語不好,我有'用戶'表中的數據庫與列'birth_date'。 是的,我想分組年齡爲 {10-20歲,21-30歲,等等}, 的用戶,然後統計具有特定年齡段的用戶總數。我想創建一個像這樣的HTML表格 Age |總用戶數 10至20 | 20 21至30 | 58 –

回答

0

你需要什麼,我相信是:

function array_get_range($array, $min, $max) { 
    return array_filter($array, function($element) use ($min, $max) { 
     return $element >= $min && $element <= $max; 
    }); 
} 

$array = [1,1,2,2,2,3,4,4,5,6,6,6,7]; 

$range13 = array_get_range($array, 1, 3); // [1, 1, 2, 2, 2, 3] 
$range45 = array_get_range($array, 4, 5); // [4, 4, 5] 
$range67 = array_get_range($array, 6, 7); // [6, 6, 6, 7] 
0

用您範圍的新數組,然後通過價值觀,並通過內部的範圍迭代。如果當前值的範圍內,記錄添加到當前範圍:

<?php 
$numbers = [1,1,2,2,2,3,4,4,5,6,6,6,7]; 
$counts = []; 
$counts[] = ["values"=> [1, 3], "records" => []]; // first value in "values" is min, second is max 
$counts[] = ["values"=> [4, 5], "records" => []]; 
$counts[] = ["values"=> [6, 7], "records" => []]; 
foreach ($numbers as $number) { 
    foreach ($counts as $key => &$value) { 
     if ($number >= $value["values"][0] && $number <= $value["values"][1]) { // if between the range, add it to the records 
      $value["records"][] = $number; 
     } 
    } 
} 
echo "<pre>"; 
foreach ($counts as $count) { 
    echo $count["values"][0]." - ".$count["values"][1]." = ".count($count["records"])." elements<br>"; 
} 

Demo

0

我覺得array_intersect()range()sizeof()/count()爲這項任務做了一個更清潔的工作。它消除了雙重條件。

代碼:(Demo

function count_range($array,$min,$max){ 
    return sizeof(array_intersect($array,range($min,$max))); 
} 

$array = [1,1,2,2,2,3,4,4,5,6,6,6,7]; 

echo count_range($array,1,3); // 6 from [1,1,2,2,2,3] 
echo count_range($array,4,4); // 2 from [4,4] 
echo count_range($array,2,7); // 11 from [2,2,2,3,4,4,5,6,6,6,7]