代码之家  ›  专栏  ›  技术社区  ›  Todd Moses

如何从PHP中第二个数组的值计算一个数组中出现的次数?

  •  0
  • Todd Moses  · 技术社区  · 15 年前

    我在PHP中有两个类似这样的数组:

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

    我需要把这些数组组合在一起,告诉它们 $cols 价值在每个 $rows 价值。

    所以我的结果应该是这样的:

    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
            )
    
        ...
    )
    

    $rows和$cols的值将根据用户的输入而改变,它们甚至可能是字符串。

    澄清:

    重复值来自数据。思考调查结果或试题。所以问题11有两个人回答1,一个人回答2。

    问题:

    如何计算$rows中出现$cols的次数并将结果添加到多维数组中?

    2 回复  |  直到 15 年前
        1
  •  1
  •   simshaun    15 年前

    退房 array_intersect() . 使用它获取相同的值,并对结果数组执行count()操作。

        2
  •  0
  •   Todd Moses    15 年前

    我想出来了。这并不像我最初想象的那么复杂。只是需要一个函数来计算和。也许它能更有效,我喜欢任何关于它的想法,但这里是:

    $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;
        }
    

    结果是:

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