1

I want to count the same values at the deepest/last level of a multidimensional array:

Array
(
[svote001] => Array
    (
        [0] => 006
        [1] => 006
        [2] => 007
    )

[svote002] => Array
    (
        [0] => 000
        [1] => 000
        [2] => 000
    )

[svote003] => Array
    (
        [0] => 002
        [1] => 003
        [2] => 001
    )
)

converted to

Array
(
[svote001] => Array
    (
        [006] => 2
        [007] => 1
    )

[svote002] => Array
    (
        [000] => 3
    )

[svote003] => Array
    (
        [001] => 1
        [002] => 1
        [003] => 1
    )
)

The counted values should additionally be sorted from high to low numbers.

2
  • Is the array always 2-dimensional? Commented Feb 12, 2014 at 21:32
  • Yes, the array is always 2-dimensional and all "inner" arrays have the same amount of values: all 3 values or 4 or 5... Commented Feb 12, 2014 at 21:38

2 Answers 2

6
foreach($array as $k => $v) {
    $result[$k] = array_count_values($v);
    arsort($result[$k]);
}
  • Loop through the array (exposing the key) to access each inner array
  • Count the values of the inner array (value will be key and count will be value)
  • Sort by the values (count) preserving the keys
Sign up to request clarification or add additional context in comments.

Comments

2

This should fit your needs:

<?php

$a = array(
    'svote001' => array("006", "006", "007"),
    'svote002' => array("000", "000", "000"),
    'svote003' => array("003", "001", "001"),
);
$resultArray = array();

foreach ($a as $arrayName => $arrayData){
    $resultArray[$arrayName] = array();
    foreach ($arrayData as $value){
        if (empty($resultArray[$arrayName][$value])){
            $resultArray[$arrayName][$value] = 1;
        }else{
            $resultArray[$arrayName][$value]++;
        }
    }
    arsort($resultArray[$arrayName]);
}

var_dump($resultArray);

Edit: AbraCadaver solution is much better, use this one. I will let the answer stay here anyway.

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.