I have an array in the following format:
array(5){
[0] =>
array(4){
['product-id'] => 8931
['product'] => 'Cake'
['description'] => 'Yellow cake'
['quantity'] => 1
}
[1] =>
array(4){
['product-id'] => 8921
['product'] => 'Cookies'
['description'] => 'Chocolate chip cookies'
['quantity'] => 2
}
[2] =>
array(4){
['product-id'] => 8931
['product'] => 'Cake'
['description'] => 'Yellow cake'
['quantity'] => 1
}
[3] =>
array(4){
['product-id'] => 8931
['product'] => 'Cake'
['description'] => 'Yellow cake'
['quantity'] => 4
}
[4] =>
array(4){
['product-id'] => 8933
['product'] => 'Cake'
['description'] => 'Chocolate cake'
['quantity'] => 1
}
}
How can I compare all the arrays to each other? In my code I have sorted all the arrays by product ID, and written a for to compare two rows at a time, but now I see why that won't work.
function cmp($a, $b){
return strcmp($a[0], $b[0]);
}
function combineArrays($arrays){
usort($arrays, "cmp");
for($i = 1; $i < count($arrays); $i++){
$f_row = $arrays[$i];
$next = $i + 1;
$s_row = $arrays[$next];
if($f_row[0] == $s_row[0]){
if($f_row[1] == $s_row[1]){
if($f_row[2] == $s_row[2]){
$q1 = (int) $f_row[3];
$q2 = (int) $s_row[3];
$total = $q1 + $q2;
unset($f_row[3]);
$f_row[5] = $total;
unset($arrays[$next]);
}
}
}
}
return $arrays;
}
What is a better way to do this?
For example, to take the first array and compare it to the next, value for value. As soon as one of the first 3 values doesn't match, you go on to compare that row to the next one. If all of the first three values match, add up the quantity value of the two arrays, assign that to the first array's quantity, and get rid of the second array. There could be more matches, so continue comparing that array until you have gone through the whole list.