计算循环内特定值的出现次数

时间:2013-11-19 16:27:50

标签: php arrays

在数组计数中,所有类别为1的类别为1后,类别将移至2计数全部为真,依此类推?

生成的数组:

foreach($_POST as $key => $data)
{
    $a = explode("_", $key);

    $f = array(
        'category' => $a[1],
        'answer' => $data
    );
   $f_data[] = $f;
}

发件人

Array
(
    [0] => Array
        (
        )

    [1] => Array
        (
            [category] => 1
            [answer] => true
        )

    [2] => Array
        (
            [category] => 1
            [answer] => true
        )

    [3] => Array
        (
            [category] => 1
            [answer] => true
        )

    [4] => Array
        (
            [category] => 1
            [answer] => false
        )

    [5] => Array
        (
            [category] => 1
            [answer] => false
        )

    [6] => Array
        (
            [category] => 1
            [answer] => true
        )

    [7] => Array
        (
            [category] => 1
            [answer] => true
        )

    [8] => Array
        (
            [category] => 2
            [answer] => true
        )

    [9] => Array
        (
            [category] => 2
            [answer] => true
        )

    [10] => Array
        (
            [category] => 2
            [answer] => true
        )

    [11] => Array
        (
            [category] => 2
            [answer] => false
        )

    [12] => Array
        (
            [category] => 2
            [answer] => true
        )

    [13] => Array
        (
            [category] => 2
            [answer] => true
        )

)

array (
   category: 1,
   count: 5
),
array(
  category: 2,
  count: 5
)

2 个答案:

答案 0 :(得分:0)

未经测试,但我相信这就是你所追求的(等待任何小错误):

foreach($_POST as $key => $data)
{
    $a = explode("_", $key);

    $f[$a[1]]['category'] = $a[1];

    if ($data == "true") {
        $f[$a[1]]['answer']++;
    }
}

答案 1 :(得分:0)

这是解决方案:

$return = array();
foreach($cont as $item) {
    if($item['answer'] == 'true') {
        $verify = false;
        foreach($return as $key => $value) {
            if($value['category'] == $item['category']) {
                $return[$key]['count']++;
                $verify = true;
                break;
            }    
        }
        if(!$verify)
             $return[] = array('category' => $item['category'], 'count' => 1);
    }
}

这是更好的解决方案......

$return = array();
foreach($cont as $item) {
    if($item['answer'] == 'true') {
        if(array_key_exists($item['category'], $return))
            $return[$item['category']]++;
        else    
            $return[$item['category']] = 1;
    }
}