我有以下数组
Array (
[0] => Array (
[0] => Array (
[productCode] => HQ768H
[startTimeLocal] => 2018-04-17 14:00:00
[endTimeLocal] => 2018-04-17 16:00:00
[totalQuantity] => 2
[amount] => 170
[extras] => Array ()
[transferReturn] =>
[subtotal] => 170
)
[1] => Array (
[productCode] => PLJ6HP
[startTimeLocal] => 2018-04-15 14:00:00
[endTimeLocal] => 2018-04-15 16:00:00
[totalQuantity] => 2
[amount] => 170
[extras] => Array ()
[transferReturn] =>
[subtotal] => 170
)
[2] => Array (
[productCode] => PLJ6HP
[startTimeLocal] => 2018-04-15 14:00:00
[endTimeLocal] => 2018-04-15 16:00:00
[totalQuantity] => 2
[amount] => 170
[extras] => Array ()
[transferReturn] =>
[subtotal] => 170
)
)
)
我正在尝试使用由productCode,startTimeLocal和totalQuantity组成的PHP创建另一个数组...但是其中两个或多个元素具有相同的productCode和相同的startTimeLocal我需要通过添加新的更新totalQuantity值,而不是添加一个新的数组元素。
我能够提出的唯一代码是一组很长的嵌套foreach循环,这些循环不会接近执行我需要的操作。我对此很陌生。如果有人可以提供帮助或指出我正确的方向,我将非常感激。感谢。
以下是我想要实现的目标......
Array (
[0] => Array (
[0] => Array (
[productCode] => HQ768H
[startTimeLocal] => 2018-04-17 14:00:00
[totalQuantity] => 2
)
[1] => Array (
[productCode] => PLJ6HP
[startTimeLocal] => 2018-04-15 14:00:00
[totalQuantity] => 4
)
)
)
答案 0 :(得分:1)
您可以通过循环旧数组来完成此操作。然后添加一个新数组作为元素(如果它尚不存在)。否则,您只需将totalQuantity
添加到现有元素。
$new_array = [];
foreach ($array as $inner_array)
foreach ($inner_array as $element) {
//check if already in $new_array and get index
$index = -1;
for ($i = 0; $i < count ($new_array); $i++)
if ($new_array[$i]['productCode'] == $element['productCode'])
if ($new_array[$i]['startTimeLocal'] == $element['startTimeLocal'])
$index = $i;
//check if it was found
if ($index == -1) {
//if not add to $new_array
$new_array[] = [
'productCode' => $element['productCode'],
'startTimeLocal' => $element['startTimeLocal'],
'totalQuantity' => $element['totalQuantity']
];
} else {
//otherwise increase totalQuantity
$new_array[$index]['totalQuantity'] += $element['totalQuantity']
}
}