将 2 个数组的值相除

Divide values from 2 arrays

我有这个数组

$a = [
     0 => [
         'period'     => '2017/2018',
         'product'    => 'AM',
         'quantity_1' => 20,
         'quantity'   => 25,
     ],
     1 => [
         'period'     => '2018/2019',
         'product'    => 'AM',
         'quantity_1' => 12,
         'quantity'   => 19,
     ],
     2 => [
         'period'     => '2017/2018',
         'product'    => 'DC',
         'quantity_1' => 20,
         'quantity'   => 25,
     ], 
     3 => [
         'period'     => '2018/2019',
         'product'    => 'DC',
         'quantity_1' => 8,
         'quantity'   => 10,
     ]
]

我们的想法是按时期和产品划分价值,在本例中我们有 2 个产品 'AM' && 'DC'。因此,将产品 AM 和产品 DC 的值从 2018/2019 划分为 2017/2018。我需要得到这样的结果:

$result = [
      0 => [
            'product'     => 'AM'
            'quantity_1'  => 12/20 = 0.6
            'quantity_2'  => 19/25 = 0.76
      ],
      1 => [
            'product'     => 'DC'
            'quantity_1'  => 8/20 = 0.4
            'quantity_2'  => 10/25 = 0.4
      ]
]

我尝试使用 foreach,但我认为存在其他一些简单的方法可以做到这一点。如果您有一些想法,我将不胜感激。谢谢你的时间。

我这样试过:

$i = 0;
    foreach ($results as $result){
        $result[] = [
            'product'       => $result['product'],
            'tonnes_prod'   => $results[$i+1]['quantity_1'] / $results[$i]['quantity_1']
        ];
        $i++;
    }

但我收到错误消息:#message: "Notice: Undefined offset: 28"

先重新制作数组,再计算结果

$temp = [];
foreach ($a as $x){
    $temp[$x['product']][$x['period']] = $x;
}

$result = [];
foreach ($temp as $key => $res){
    $result[] = [
        'product'       => $key,
        'quantity_1'   => $res['2018/2019']['quantity_1'] / $res['2017/2018']['quantity_1'],
        'quantity_2'   => $res['2018/2019']['quantity'] / $res['2017/2018']['quantity'],
    ];
}

demo