我如何使用php获取每个年龄段的人数

时间:2018-08-09 08:50:13

标签: php

请检查以下内容:

Array
(
    [0] => 46-65
    [1] => 7-12|31-45
    [2] => 31-45
    [3] => 31-45
    [4] => 66+
    [5] => 18-30
    [6] => 46-65
    [7] => 13-17|46-65

我在这里将字符串转换为数组,然后进入数组以下:

Array
(
    [0] => Array
        (
            [0] => 46-65
        )

    [1] => Array
        (
            [0] => 7-12
            [1] => 31-45
        )

    [2] => Array
        (
            [0] => 31-45
        )

    [3] => Array
        (
            [0] => 31-45
        )

    [4] => Array
        (
            [0] => 66+
        )

    [5] => Array
        (
            [0] => 18-30
        )

    [6] => Array
        (
            [0] => 46-65
        )

    [7] => Array
        (
            [0] => 13-17
            [1] => 46-65
        )

    [8] => Array
        (
            [0] => 31-45
        )

    [9] => Array
        (
            [0] => 31-45
        )

    [10] => Array
        (
            [0] => 31-45
        )

    [11] => Array
        (
            [0] => 18-30
        )

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

    [13] => Array
        (
            [0] => 46-65
        )

    [14] => Array
        (
            [0] => 7-12
            [1] => 31-45
        )

    [15] => Array
        (
            [0] => 18-30
        )

    [16] => Array
        (
            [0] => 18-30
            [1] => 31-45
        )

    [17] => Array
        (
            [0] => 18-30
        )

    [18] => Array
        (
            [0] => 31-45
        )

    [19] => Array
        (
            [0] => 18-30
        )

    [20] => Array
        (
            [0] => 13-17
            [1] => 18-30
            [2] => 46-65
        )
}

我以字符串格式存储了年龄组,因为每一行可以有多个年龄组。之后,我转换为数组。 我怎样才能得到像46-65岁这样的每个年龄段的人数的6倍18-30是8倍。 我在这里想要每个年龄段的人数

2 个答案:

答案 0 :(得分:0)

此代码应适用于此

<?php
$selections = [/** your array here */];
$counted = [];

// Loop full list
foreach($selections as $selection) {

    // Loop age elements in list
    foreach ($selection as $age) {

        // If not already counted initialise age range
        if(!isset($counted[$age])) {
            $counted[$age] = 0;
        }

        // Increment age range
        $counted[$age]++;
    }
}

var_dump($counted);

答案 1 :(得分:0)

我不确定我是否完全理解汤姆的问题。尝试这样的事情。 这将返回一个数组,该数组具有作为组的键和作为满足条件的次数的值。 我使用了第二个数组,或者您已经细分为子数组

$groups = [];
foreach($array as $subArray) {
  foreach ($subArray as $group) {
    if (isset($groups[$group])) {
      $groups[$group] += 1;
    } else {
      $groups[$group] = 1;
    }
  }
}