简体   繁体   English

PHP将多维数组的值相乘

[英]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). 我想做的是找到所有橙子的值乘以(4 * 2 * 2.20),将所有苹果的值乘以(2 * 1.82)。 The amount of arrays of values is variable and the amount of values inside the arrays is variable. 值数组的数量是可变的,数组内部的值数量是可变的。

This uses a combination of foreach , isset , and your run-of-the-mill if/else statements. 它使用了foreachissetisset if/else语句的组合。

$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. 应该是不言自明的,因为您要做的只是使用相同的键来获取所有最低层元素的乘积。

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: 尽管sjagr的答案是可能的最佳解决方案,但我有array_column (PHP 5> = 5.5.0)的另一种方法,它仅需要一个foreach循环:

<?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 演示: https : //eval.in/82322

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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