pattyd
pattyd

Reputation: 6160

Count values in specific position in multidimensional array

I have a multidimensional array that looks like this:

array(6) {
  [0]=>
  array(6) {
    [0]=>
    string(5) "email"
    [1]=>
    string(5) "vote1"
    [2]=>
    string(5) "vote2"
    [3]=>
    string(5) "vote3"
    [4]=>
    string(5) "vote4"
    [5]=>
    string(5) "vote5"
  }
  [1]=>
  array(6) {
    [0]=>
    string(5) "[email protected]"
    [1]=>
    string(1) "A"
    [2]=>
    string(1) "B"
    [3]=>
    string(1) "C"
    [4]=>
    string(1) "D"
    [5]=>
    string(1) "E"
  }
  [2]=>
  array(6) {
    [0]=>
    string(5) "[email protected]"
    [1]=>
    string(1) "A"
    [2]=>
    string(1) "B"
    [3]=>
    string(1) "C"
    [4]=>
    string(1) "D"
    [5]=>
    string(1) "E"
  }
  [3]=>
  array(6) {
    [0]=>
    string(5) "[email protected]"
    [1]=>
    string(1) "A"
    [2]=>
    string(1) "B"
    [3]=>
    string(1) "C"
    [4]=>
    string(1) "D"
    [5]=>
    string(1) "E"
  }
  [4]=>
  array(6) {
    [0]=>
    string(5) "[email protected]"
    [1]=>
    string(1) "A"
    [2]=>
    string(1) "B"
    [3]=>
    string(1) "C"
    [4]=>
    string(1) "D"
    [5]=>
    string(1) "E"
  }
  [5]=>
  array(6) {
    [0]=>
    string(5) "[email protected]"
    [1]=>
    string(1) "A"
    [2]=>
    string(1) "B"
    [3]=>
    string(1) "C"
    [4]=>
    string(1) "D"
    [5]=>
    string(1) "E"
  }
}

I want to count how many times each value occurs at position [1] of each array.

I have tried many things including array_count_values(), but this doesn't allow the option to count occurrences in just a certain position of each array. I'm not quite sure how to go about this issue because the array is multidimensional and I have never had to deal with just counting the values at a specific position.

I apologize if the answer to this is blatantly obvious, I've been working on this issue for a few hours but to no avail, but I also am a beginner when it comes to arrays, especially multidimensional. All ideas are welcome :)

Upvotes: 0

Views: 379

Answers (2)

LF-DevJourney
LF-DevJourney

Reputation: 28529

use array_column($array, 1) to get position[1] elements as array; Then use your array_count_values() to count them.

<?php
$array = [[1,2,3],[2,3,4]];
var_dump(array_count_values ( array_column($array,1) ));

Upvotes: 0

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167172

What you can do is, you can loop through the array and put the values of [1] into another array, and apply array_count_values on the resultant array.

$a = array();
foreach ($arr as $ar) {
  $a[] = $ar[1];
}
print_r(array_count_values($a));

This will give you:

  • vote1: 1
  • A: 5

If the above is what you are looking for? If you want a shorter version, you can also use array_column.

Upvotes: 2

Related Questions