Manipulation de tableau ( multiplication )

PandiPanda
Invité n'ayant pas de compte PHPfrance

28 mars 2006, 16:32

Bonjour tlm, y a til un moyen de multiplier les valeures de 2 tableaus de meme nature :

Code : Tout sélectionner

$total_1= array("01" => 1,"02" => 0,"03" => 2,"04" => 0); [b]X[/b] $total_2= array("01" => 3,"02" => 5,"03" => 2,"04" => 0); = $total_3= array("01" => 3,"02" => 0,"03" => 4,"04" => 0);
merci

Eléphant du PHP | 451 Messages

28 mars 2006, 17:45

Est-ce qu'une solution à base de foreach te conviendrait ?
<?php
// affectation
$total_1= array("01" => 1,"02" => 0,"03" => 2,"04" => 0);
$total_2= array("01" => 3,"02" => 5,"03" => 2,"04" => 0); 
// multiplication (resultat dans $total_3)
foreach($total_1 as $key => $val) {
	$total_3[$key]=$total_1[$key]*$total_2[$key];
}
// verification
foreach($total_3 as $key => $val) {
	echo "<BR>".$key." -> ".$val;
}

?>
Jpaul
J'essaye d'aider : parfois je fais des erreurs, on me les corrige et j'apprends un peu plus. Super ce forum :)

Modérateur PHPfrance
Modérateur PHPfrance | 7636 Messages

28 mars 2006, 19:06

proposition avec array_map()
function mult($a, $b) 
{
    return $a * $b;
}  

$total_1= array("01" => 1,"02" => 2,"03" => 2,"04" => 0);

$total_2= array("01" => 3,"02" => 5,"03" => 2,"04" => 0);     
 
$c = array_map("mult", $total_1, $total_2);
print_r($c);

/!\ Avant de poster se documenter et rechercher.
Qui ne sait pas rendre un service n'a pas le droit d'en demander.
MaBrute