How to multiply numeric array values of similar keys in Php?
$a = array ('x' => 2, 'y' => 3);
$b = array ( 'y' => 2, 'z' =>开发者_如何学Python; 3);
// $c = $a * $b;
// i would like to have
// $c = array ('x' => 0, 'y' => 6, 'z' => 0);
If you want to multiply any similar keys together, you will need to get a list of the keys. array_keys would appear to be just the function for that.
function foo($a, $b)
{
foreach(array_keys($a) as $i)
{
if(array_key_exists($i, $b){ // exists in a and b
$result[$i] = $a[$i]*$b[$i];
}else{ // exists and a but not b
$result[$i] = 0;
}
}
foreach(array_keys($b) as $i)
{
if(not array_key_exists($i, $a){ //exists in b but not i a
$result[$i] = 0;
}
}
return $result
}
This will (hopefully) work for any set of keys you hand in, not just x, y, and z.
You could use array_map and abuse bcmul for this purpose:
array_map( 'bcmul', $a, $b ) == $a * $b
You'll have to use a library or define the cross product yourself:
function cross_product($a, $b)
{
return array( $a['y'] * $b['z'] - $a['z'] * $b['y'], ...
}
http://en.wikipedia.org/wiki/Cross_product
After further examination of what you're doing, it looks as though you'd like something along the lines of:
function multiply_arr($a, $b)
{
return array($a['x'] * $b['x'], $a['y'] * $b['y'], $a['z'] * $b['z]);
}
again, you'll have to make your own function, and you ought to do some error checking in case a value is undefined.
精彩评论