简体   繁体   中英

How to multiply two arrays of different length?

I have two arrays of different length:

$a = array(10, 20, 30, 40, 50);
$b = array(1, 2, 3);

I'd like to multiply them (eg $c=array_mult($a, $b) ) in the way, that the shorter array is repeated. $c should be 10, 40, 90, 40, 100 since:

10 * 1 = 10
20 * 2 = 40
30 * 3 = 90

40 * 1 = 40
50 * 2 = 100

Is there a built-in function in PHP to fulfill this task? How can I solve this problem efficiently?

There isn't a built-in function to do that. You can do it with a foreach and the modulo operator pretty easily, though:

$c = array();
$len = count($b);
foreach($a as $key => $value){
    $c[$key] = $value*$b[($key % $len)];
}

Use a for loop with modulus operator ( % ):

$a = array(10, 20, 30, 40, 50);
$b = array(1, 2, 3);

$aCount = count($a);
$bCount = count($b);

for ($i=0; $i < $aCount; $i++) { 
    $result[] = $b[$i % $bCount] * $a[$i];
}

Output:

Array
(
    [0] => 10
    [1] => 40
    [2] => 90
    [3] => 40
    [4] => 100
)

Demo


UPDATE: If you'd like to have the shorter array repeated regardless of their order of length, you can use the following solution:

$a = array(10, 20);
$b = array(1, 2, 3);

$smallArr = min($a, $b);
$largeArr = max($a, $b);

$smallCount = count($smallArr);
$largeCount = count($largeArr);

for ($i=0; $i < $largeCount; $i++) { 
    $result[] = $smallArr[$i % $smallCount] * $largeArr[$i];
}

Output:

Array
(
    [0] => 10
    [1] => 40
    [2] => 30
)

Demo

first have $b of the same length than $a :

$i=0;
while(count($b) < count($a)){
    if($i > count($b){$i=0;}
    $b[] = $b[$i];
    $i++;
}

Then multiply both arrays :

$total = array_map(function($x, $y) { return $x * $y; }, $a, $b);

$total contains what you want.

Throwing in a MultipleIterator solution (requires >= 5.5):

$a = array(10, 20, 30, 40, 50);
$b = array(1, 2, 3);

$m = new MultipleIterator(MultipleIterator::MIT_KEYS_ASSOC);
$m->attachIterator(new InfiniteIterator(new ArrayIterator($a)), 'a');
$m->attachIterator(new InfiniteIterator(new ArrayIterator($b)), 'b');

$c = array();

foreach (new LimitIterator($m, 0, max(count($a), count($b))) as $both) {
        $c[] = $both['a'] * $both['b'];
}

print_r($c);

I'm using the InfiniteIterator to repeat the inner iterator as many times as is necessary; both iterators are then attached to the MultipleIterator that will simultaneously iterate over both inner iterators. It's effectively another InfiniteIterator , so it needs to be limited.

Finally, the LimitIterator will iterate over its inner iterator max(count($a), count($b)) times, the size of the biggest array.

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