我有这个数组
$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'。因此,将产品2018/2019
和产品2017/2018
的值AM
除以DC
。我需要得到这样的结果:
$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"
答案 0 :(得分:1)
首先重新制作数组,然后计算结果
$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'],
];
}