Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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.

share|improve this question
    
Is the array always 2-dimensional? –  Flixer Feb 12 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... –  Felix Bernhard Feb 12 at 21:38

2 Answers 2

up vote 2 down vote accepted
foreach($array as $k => $v) {
    $result[$k] = array_count_values($v);
    arsort($result[$k]);
}
print_r($result);
share|improve this answer
1  
arsort, otherwise excellent. –  Wrikken Feb 12 at 21:41
    
Thank you really much! Awesome –  Felix Bernhard Feb 12 at 21:46

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.

share|improve this answer
    
Thanks anyway :) –  Felix Bernhard Feb 12 at 21:45

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.