1

I have the following array, which is a load of arrays nested in a bigger array:

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
        )

)

I want to do the equivalent of array_count_values on this array, such that I get 15 => 3, 5 => 2 and 2 => 10. How do I un-nest the arrays to do this?

2 Answers 2

2

You may want to try reforming your array to count:

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

// Now get the counts
$the_count = array_count_values($count_array);
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks PhpMyCoder. I started with a different method and then changed mid-way, forgetting to update the foreach() to a different level. Much appreciated!
1

I think array map will also work for this

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.