douzhong6480 2013-12-24 01:17
浏览 25
已采纳

PHP乘以多维数组的值

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.

  • 写回答

2条回答 默认 最新

  • douqiang6448 2013-12-24 01:26
    关注

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100