I have a multi-dimensional array of values posted from a form and I am trying to not just de-dupe them, but sum the values from the duplicated arrays so that these can be posted as one, larger value.
The array posted is as follows:
Array
(
[0] => Array
(
[0] => 4
[1] => 27/11/2013
)
[1] => Array
(
[0] => 4
[1] => 27/11/2013
)
[2] => Array
(
[0] => 2
[1] =>
)
[3] => Array
(
[0] => 2
[1] =>
)
)
For each sub-array, value 0 is a quantity and value 1 is a date (which is optional). The final entry in the array is a qty of 2 with a blank date which was added automatically because the required total was 12.
I am then looking through the sub-arrays using a foreach loop (below) to check for duplicate dates.
foreach ($qty_date_array as $key => $value)
{
if(in_array($value[1], $exists) && !in_array($value[1], $duplicates))
{
$duplicates[] = $value[1];
}
else
{
$exists[] = $value[1];
}
The output of $duplicates is...
Array
(
[0] => 27/11/2013
[1] =>
)
I guess I then want to look at the values reached in the array and foreach of them, find the associated original qty value(s) and sum them, but I'm not sure how to proceed further.
Array_search will only return the key, so I guess that is out (and I cannot write the Qty as the key because it may be a duplicate value). Other array functions i've dabbled with, such as array_unique, collapse the array based on the indexes, so lose data.
The final multidimensional array would ideally look something like this:
Array
(
[0] => Array
(
[0] => 8
[1] => 27/11/2013
)
[2] => Array
(
[0] => 4
[1] =>
)
)
If someone can suggest a more efficient way to achieve this, I'm open to all suggestions!