4

2次元配列をループして、列の組み合わせの合計を自動的に取得しようとしています。

4列の$aという配列があるとします:0,1,2,3、

$a=array();
$a[0][0]=1;
$a[0][1]=3;
$a[0][2]=5;

$a[1][0]=10;
$a[1][1]=2;  
$a[1][2]=5;
$a[1][3]=7;

$a[2][0]=9;
$a[2][1]=8;  
$a[2][2]=9;
$a[2][3]=8;

$a[3][0]=9;
$a[3][1]=8;  
$a[3][2]=9;
$a[3][3]=8;
$a[3][4]=1;

そして、私はこのコードを使用して、sum(0,0; ​​1,0; 2; 0,3; 0)などの列のすべての組み合わせを合計しようとしています

for($i=0;$i<count($a[0]);$i++){
for($l=0;$l<count($a[1]);$l++){ 
for($s=0;$s<count($a[2]);$s++){ 
for($m=0;$m<count($a[3]);$m++){
 echo $sum[]= $a[0][$i]+$a[1][$l]+$a[2][$s]+$a[3][$m]; 
 echo $sum;
  echo "<br>";
   } 
   } 
 }
 }

 ?>

そして、コードは機能します。問題は、これらのforループを手動で実行していることです。列数のカウントを挿入することで、これを単純化できる方法が必要ですか?

私は次のようなことを試みました

$numberofcolumns=4; 

for($n=0;$n<$numberofcolumns;$n++){
for($i=0;$i<count($a[$n]);$i++){
for($m=0;$m<count($a[$n+1]);$m++){
echo $sums[]= $a[$n][$i]+$a[$n+1][$m];
}
}
}

しかし、それは機能しません。forループを単純化して、各列にforループを手動で入力する必要がないようにする方法が必要です。

誰か手がかりがありますか?

4

4 に答える 4

1

使用できますRecursiveIteratorIterator

試す

$a = array ();
$a [0] [0] = 1;
$a [0] [1] = 3;
$a [0] [2] = 5;

$a [1] [0] = 10;
$a [1] [1] = 2;
$a [1] [2] = 5;
$a [1] [3] = 7;

$a [2] [0] = 9;
$a [2] [1] = 8;
$a [2] [2] = 9;
$a [2] [3] = 8;

$a [3] [0] = 9;
$a [3] [1] = 8;
$a [3] [2] = 9;
$a [3] [3] = 8;
$a [3] [4] = 1;

$sum = 0;
$array = new RecursiveIteratorIterator ( new RecursiveArrayIterator ( $a ) );
foreach ( $array as $key => $value ) {
        $sum += $value;
}
echo $sum;

出力

 102

$array = new RecursiveIteratorIterator ( new RecursiveArrayIterator ( $a[1] ) );各セクションの合計を取得するために使用します...

于 2012-05-06T18:22:13.870 に答える
1

これには再帰または単純にネストされたループを使用できますが、組み合わせや順列を使用すると、可能性の総数が爆発的に膨大になり、コードを実行できないほど多くのメモリを消費する可能性があります。イテレータの使用は、CPU 効率とメモリ効率をトレードオフする良い方法です。これが私が書いたイテレータです。

class CartesianProductIterator implements Iterator {
    protected $iterators;

    function __construct(array $iters) {
        $this->iterators = $iters;
    }

    function rewind() {
        foreach ($this->iterators as $it) {
            $it->rewind();
        }
    }

    function current() {
        $values = array();
        foreach ($this->iterators as $it) {
            $values[] = $it->current();
        }
        return $values;
    }

    function key() {
        return null;
    }

    function next() {
        /*      
        loop them in reverse, but exclude first
        why? example, odometer: 55199
        you always check the rightmost digit first to see if incrementing it would roll it over and need to be "rewound" to 0, 
        which causes the digit to the left to increase as well, which may also cause it to roll over as well, and so on...
        looping in reverse operates from right column to the left.
        we dont rewind the first column because if the leftmost column is on its last element and needs to roll over
        then this iterator has reached its end, and so rewind() needs to be explicitly called 
        */
        for ($i = count($this->iterators) - 1; $i > 0; --$i) {
            $it = $this->iterators[$i];
            $it->next();
            if ($it->valid()) {
                // were done advancing because we found a column that didnt roll over
                return;
            } else {
                $it->rewind();
            }
        }

        //if execution reached here, then all of the columns have rolled over, so we must attempt to roll over the left most column
        $this->iterators[0]->next();
    }

    function valid() {
        return $this->iterators[0]->valid();
    }
}

次に、次のように使用します

$iterators = array();
foreach ($a as $columnNumber => $values) {
    $iterators[] = new ArrayIterator($values);
}
foreach (new CartesianProductIterator($iterators) as $combo) {
    // combo has 1 value from each of the ArrayIterators we instantiated
    printf("summing %s = %d\n", join('+', $combo), array_sum($combo));
}

デモはこちら http://codepad.org/UasdgvWf

于 2012-05-06T20:49:18.670 に答える
0

私があなたを正しく理解しているなら、この関数はうまくいくはずです:

<?php
function recursive_sum($arr) { 

    $sum = 0;

    foreach($arr as $value) { 
        if(is_array($value)) {
            $sum += recursive_sum($value);
        }
        else { 
            $sum += $value;
        }
    }

    return $sum;
}  
?>

recursive_sum($a)次のように、配列内のすべての値の合計を取得するために呼び出すだけです。

<?php
    echo recursive_sum($a);
?>    
于 2012-05-06T18:31:24.707 に答える
0
<? //PHP 5.4+
$a=[];
$a[0][0]=1;
$a[0][1]=3;
$a[0][2]=5;

$a[1][0]=10;
$a[1][1]=2;  
$a[1][2]=5;
$a[1][3]=7;

$a[2][0]=9;
$a[2][1]=8;  
$a[2][2]=9;
$a[2][3]=8;

$a[3][0]=9;
$a[3][1]=8;  
$a[3][2]=9;
$a[3][3]=8;
$a[3][4]=1;

//This is downright evil, but it works.
eval(\array_reduce(
  \array_reverse(\array_keys($a)),
  static function($eval, $key){
    return "foreach(\$a[$key]as\$i$key)$eval+\$i$key";
  },
  '{echo$sum[]=0') . ';echo"$sum<br/>";}');
?>
于 2012-05-06T20:07:45.843 に答える