在临时数组中添加计数值

时间:2014-12-02 14:43:05

标签: php arrays

我在计算foreach循环内部两天之间的差异。

foreach ($result as $key => $value) {
    # code...

    //$temp[$value->user_id]=$value->user_id;
    $count_dates=daysBetween($value->user_source_history_added,$current_date);
    $tmp_array[$count_dates][] = $count_dates;
}

在调试tmp_array时,我得到类似的东西。

Array
(
    [0] => Array
        (
            [0] => 0
            [1] => 0
            [2] => 0
            [3] => 0
            [4] => 0
            [5] => 0
            [6] => 0
        )

    [1] => Array
        (
            [0] => 1
        )

    [3] => Array
        (
            [0] => 3
            [1] => 3
            [2] => 3
            [3] => 3
        )
)

现在我要计算0,1,2,3,3等的数量。所以现在有7 0&1和1 1&4和4 3&s。 我如何获得所有这些数字的计数,以及如何限制它只得到数组直到数组20?

我试过了:

foreach($tmp_array as $tmp_val)
{
    count($tmp_val)
}

但我得到主阵列的数量为3

4 个答案:

答案 0 :(得分:0)

如果你想把所有东西的数量加在一起:

$count = 0;
foreach($tmp_array as $tmp_subarray)
{
    foreach($tmp_subarray as $tmp_val) {
        if($count < 20) {
            $count++;
        }
    }
}

如果你想要1s,2s,3s等的数量:

$count = array();
foreach($tmp_array as $tmp_subarray)
{
    foreach($tmp_subarray as $tmp_val) {
        if($count[$temp_val]) {
            $count[$temp_val]++;
        } else {
            $count[$temp_val] = 1;
        }
    }
}

答案 1 :(得分:0)

这将计算数组的所有值,无论假设值是数组或数字有多少维度。这将一直运行,直到主数组达到$ key == 20。

$total = 0;

function addToTotal($number) {
    glob $total;
    $total = $total + $number;
}

function countArrayValues($array) {
    foreach($array as $key => $value) {
        if(is_array ($value) {
            countArrayValues($value);
        } else {
            addToTotal($value);
        }
    }
}

$mainArray; // <-- your array;

foreach($mainArray as $key => $value) {
    if($key <= 20) {
        countArrayValues($value);
    } else {
        break;
    }
}

echo $total;

答案 2 :(得分:0)

试试这个:

$array_number_of_numbert = array();
foreach($tmp_array as $tmp_val_num => $tmp_val)
{
    $array_number_of_numbert[$tmp_val_num]= $tmp_val;
}
for($i = 0; $i <=20; $i++)
{
    if(isset($array_number_of_numbert[$i])) echo count($array_number_of_numbert[$i])." ". $i."'s\n";
}

答案 3 :(得分:0)

更新if($count_array<=20){}

这是一个通用的解决方案,它将考虑你的$ temp数组中的任何数字,它会将此数字存储为此数组中的记录

$found_numbers=array();
$results=array();
$count_array=0;
    foreach($tmp_array as $first_array)
{   $count_array++;
    foreach($first_array as $second_array)
    { 
      if($count_array<=20){
        if (in_array($second_array, $found_numbers)) {
          $results[$second_array][0]++;
        }
        else{
         array_push($found_numbers,$second_array);
         $results[$second_array] = array();
         array_push($results[$second_array],1);
         }
      } 
    }
}

//获取数组中n号的数量,你只需输入print($ results [n] [0]);

print($results[0][0]); //will give you 7
print($results[n][0]);  //will give the record of the number n in your array