开发者

How to count the number of occurrences in one array from the values of a second array in PHP?

I have 2 arrays in PHP that look something like this:

$rows = array(11,12,14,14,11,13,12,11);
$cols = array(1,2,1,2,2,2,1,1);

I need to combine these arrays in a way that tells how many of each $cols value is in each $rows value.

So my result should look something like this:

Array
(
    [0] => Array
        (
            [row] => 11
            [1] => 2 //the count of 1 cols for 11
            [2] => 1 //the count of 2 cols for 11
        )

    [1] => Array
        (
            [row] => 12
            [1] => 1
            [2] => 1
        )

    ...
)

The values of $rows and $cols will change based upon the users input, they may even be strings.

Clarification:

The duplicates values 开发者_如何学Ccome from the data. Think survey results or test questions. So question 11 had 2 people answer 1 and 1 person answer 2.

Question:

How do I count the number of occurrences of $cols in $rows and add the results into a multidimensional array?


Check out array_intersect(). Use it to get values that are the same and do a count() on the resulting array.


I figured it out. It was not as complicated as I first thought. Just needed a function to calculate the sum. Perhaps it could be more efficient, I would love any ideas on that, but here it is:

$rowColumns = array();

            for($i=0;$i<=$count-1;$i++)
            {
                $currentRow = $rows[$i];
                $currentCol = $cols[$i];

                //count occurences of columns in row
                $colSum = $this->getColumnOccurences($count,$rows,$cols,$currentRow,$currentCol);

                $rowColumns[$currentRow][$currentCol] = $colSum;
            }

private function getColumnOccurences($count,$rows,$cols,$rowValue,$colValue)
    {
        $retValue = 0;

        for($i=0;$i<=$count-1;$i++)
        {
            if($rows[$i] == $rowValue && $cols[$i] == $colValue)
            {
                $retValue = $retValue + 1;
            }   
        }

        return $retValue;
    }

The result is:

Array ( 
        [11] => Array ( [1] => 2 [2] => 1 ) 
        [12] => Array ( [1] => 1 [2] => 1 ) 
        [13] => Array ( [2] => 1 ) 
        [14] => Array ( [1] => 1 [2] => 1 ) 
      )
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜