使用嵌套计算数组的值

时间:2012-07-29 02:45:36

标签: php arrays

我有以下数组,这是一个嵌套在更大数组中的数组加载:

Array
(
    [0] => Array
        (
            [vote_for] => 15
        )

    [1] => Array
        (
            [vote_for] => 15
        )

    [2] => Array
        (
            [vote_for] => 15
        )

    [3] => Array
        (
            [vote_for] => 5
        )

    [4] => Array
        (
            [vote_for] => 5
        )

    [5] => Array
        (
            [vote_for] => 2
        )

    [6] => Array
        (
            [vote_for] => 2
        )

    [7] => Array
        (
            [vote_for] => 2
        )

    [8] => Array
        (
            [vote_for] => 2
        )

    [9] => Array
        (
            [vote_for] => 2
        )

    [10] => Array
        (
            [vote_for] => 2
        )

    [11] => Array
        (
            [vote_for] => 2
        )

    [12] => Array
        (
            [vote_for] => 2
        )

    [13] => Array
        (
            [vote_for] => 2
        )

    [14] => Array
        (
            [vote_for] => 2
        )

)

我想在这个数组上做相当于array_count_values的操作,这样我得到15 => 35 => 22 => 10。如何取消嵌套数组才能执行此操作?

2 个答案:

答案 0 :(得分:2)

你可能想尝试改造你的数组来计算:

$count_array = array();
foreach ($arr as $v) {
   $count_array[] = $v['vote_for'];
}

// Now get the counts
$the_count = array_count_values($count_array);

答案 1 :(得分:1)

我认为数组地图也适用于此

$count_array = array_map(function($item) { return $item['vote_for']; }, $array);
$the_count = array_count_values($count_array);