从数组中计算相同的类别,并使用其计数和类别名称存储在新数组中

时间:2016-05-03 05:31:19

标签: php arrays foreach

我有一个数组,我从数据库查询响应中得到。

现在我想计算相同的类别并在option_name数组中打印。 我已尝试使用不同的数组函数,但希望得到欲望输出。

我有一个想法是采用新数组并使用foreach循环推送它,但不知道如何使用代码实现。请帮我解决一下。

Array
(
    [0] => Array
        (
            [CNC] => Array
                (
                    [id] => 5
                    [category_id] => 68
                )

            [GVO] => Array
                (
                    [option_name] => Actors
                )

        )

    [1] => Array
        (
            [CNC] => Array
                (
                    [id] => 11
                    [category_id] => 72
                )

            [GVO] => Array
                (
                    [option_name] => Cricketers
                )

        )

    [2] => Array
        (
            [CNC] => Array
                (
                    [id] => 3
                    [category_id] => 72
                )

            [GVO] => Array
                (
                    [option_name] => Cricketers
                )

        )

    [3] => Array
        (
            [CNC] => Array
                (
                    [id] => 4
                    [category_id] => 74
                )

            [GVO] => Array
                (
                    [option_name] => Musician 
                )

        )

    [4] => Array
        (
            [CNC] => Array
                (
                    [id] => 7
                    [category_id] => 76
                )

            [GVO] => Array
                (
                    [option_name] => Directors
                )

        )

    [5] => Array
        (
            [CNC] => Array
                (
                    [id] => 6
                    [category_id] => 76
                )

            [GVO] => Array
                (
                    [option_name] => Directors
                )

        )
)

欲望输出:

Array
(
    [Actors] => 1
    [Cricketers] => 2
    [Musician] => 1
    [Directors] => 2
)

提前致谢!

3 个答案:

答案 0 :(得分:1)

您可以通过在关键数组中递增计数器来计算option_name值,其中键为option_name

$counts = [];

foreach($array as $v) {
    if(!isset($counts[$v['GVO']['option_name']])) {
        $counts[$v['GVO']['option_name']] = 0;
    }

    $counts[$v['GVO']['option_name']]++;
}

print_r($counts);

答案 1 :(得分:1)

您只需使用foreach

一样遍历数组
$result = [];
foreach($arr as $k => $v){
    if(isset($result[$v['GVO']['option_name']])){
        $result[$v['GVO']['option_name']] += 1;
    }else{
        $result[$v['GVO']['option_name']] = 1;
    }
}

print_R($result);

答案 2 :(得分:1)

试试这个:

$new_arr = array();
foreach(array_column($your_arr, 'option_name') as $value){
    if(in_array($value, $new_array)){
        $new_array[$value] = $new_array[$value]+1;
    }else{
        $new_array[$value] = 1;
    }
}

<强>输出

Array
(
    [Actors] => 1
    [Cricketers] => 2
    [Musician] => 1
    [Directors] => 2
)