scottphpnewbie
scottphpnewbie

Reputation: 3

PHP multiply values of a multidimensional array

I've tried searching for this as I don't think it's that unique that no one has tried to do it. I just can't figure out the right keywords to search for to find my answer!

I have this array

array(
 0 => array(
      'oranges'=> 4.00,
      'apples' => 2.00,
      ),
 1 => array(
      'oranges' => 2.00,
      'apples' => 1.82,
      'peaches' => 1.2,
      ),
 2 => array(
      'oranges' => 2.20,
      ),
);

What I want to do is find the value of all the oranges values multiplied together so (4 * 2 * 2.20) and all the values of apples multiplied together so (2 * 1.82). The amount of arrays of values is variable and the amount of values inside the arrays is variable.

Upvotes: 0

Views: 2217

Answers (2)

user2680766
user2680766

Reputation:

Though sjagr’s answer is the best solution possible, I have an alternative approach with array_column (PHP 5 >= 5.5.0) which requires only one foreach loop:

<?php
$arr = array(
    array(
        "oranges" => 4.00,
        "apples" => 2.00
    ),
    array(
        "oranges" => 2.00,
        "apples" => 1.82,
        "peaches" => 1.2
    ),
    array(
        "oranges" => 2.20
    )
);
$_arr = array();
    foreach(array("oranges", "apples", "peaches") as $val){
    $_arr[$val] = array_product(array_column($arr, $val));
    }
print_r($_arr);
?>

The result will be:

Array
(
    [oranges] => 17.6
    [apples] => 3.64
    [peaches] => 1.2
)

Demo: https://eval.in/82322

Upvotes: 2

sjagr
sjagr

Reputation: 16502

This uses a combination of foreach, isset, and your run-of-the-mill if/else statements.

$products = array();
foreach ($array as $a) {
    foreach ($a as $key => $value) {
        if (!isset($products[$key])) $products[$key] = $value;
        else $products[$key] = $products[$key] * $value;
    }
}

var_dump($products);

Should be self-explanatory since all you're doing is taking the product of all of the lowest level elements with the same keys.

Upvotes: 3

Related Questions