简体   繁体   中英

multiplication with *=

I have an array with these values:

array
  0 => 
    array
      0 => int 1
      1 => float 0.125
      2 => float 0.5
      3 => float 3
  1 => 
    array
      1 => int 1
      2 => float 5
      3 => float 7
      0 => float 8
  2 => 
    array
      2 => int 1
      3 => float 3
      0 => float 2
      1 => float 0.2
  3 => 
    array
      3 => int 1
      0 => float 0.33333333333333
      1 => float 0.14285714285714
      2 => float 0.33333333333333

And i want for each group the multiplication of each row like:

1*0.125*05*3

I am trying this code:

$final= array_fill(0, count($matrix), 0);
for ($i = 0; $i < count($matrix); $i++) {
    $a = 1;
    for ($j = 0; $j < count($matrix)-1; $j++) {
        $final[$i] *= $matrix[$i][$j]*$matrix[$i][$a];
        $a++;
    }
}

but i got 0 for each multiplication row.

The code works well with +=, but:

1*0.125*05*3 = 0.1875 (this is the objective)

is different of

1*0.125+0.125*0.5+*0.5*3 = 16875

Any idea ?

Can you not just do

$final = array();
foreach( $matrix as $arr ) {
    $final[] = array_product( $arr );
}

print_r( $final );

Which results in

Array ( [0] => 0.1875 [1] => 280 [2] => 1.2 [3] => 0.015873015873015 )

Alternatively, if you want to continue to do it your way:

$final= array_fill(0, count($matrix), 1);
for ($i = 0; $i < count($matrix); $i++) {
    for ($j = 0; $j < count($matrix); $j++) {
        $final[$i] *= $matrix[$i][$j];
    }
}

I removed the -1 because that meant it missed the last element take 1*5*8*7 for example. Your way = 40 because the 7 was never multiplied. The above outputs the same result.

The neutral element for the multiplication is 1, not 0. You're filling your final array with zeros with this statement

$final= array_fill(0, count($matrix), 0);

and, obviously, when you do

$final[$i] *= $matrix[$i][$j];

everything will be zero as well. Thus, you have to replace the first line with this one:

$final= array_fill(0, count($matrix), 1);

0 *任何东西都是0。您将数组初始化为全0。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM