I have an array like this, created from a MySQL result set:
$items[] = array(
"item_id" => $item["ID_ITEM"],
"item_count" => $itemfinal["BUNDLE"],
// other values here
);
There can be multiple rows with an identical $item_id and I’d like to create a new array with all the values intact, but with items of the same $item_id combined into one with a TOTAL of the $item_count.
Despite my efforts to figure it out, I’m afraid I’m stumped as to how to do that.
Thank you, StarLion. However, I do need to keep the original array intact.
I was assuming I’d need to create a new array, either by extracting the information I need from the original, or by pulling the data from the database again and cross referencing it against the original.
If you want to do it in php then code like this should do it:
$newArray = array(); // here we will accumulate grouped data
foreach ($originalArray as $row) { // loop through ungrouped data from db
if (isset($newArray[$row['item_id']])) {
// another occurence of this item_id
$newArray[$row['item_id']]['item_count'] += $row['item_bundle'];
} else {
// first occurence of item_id
$newArray[$row['item_id']] = array(
'item_id' => $row['item_id'],
'item_count' => $row['item_bundle'],
'item_description' => $row['item_description'],
'item_price' => $row['item_price'],
);
}
I assume that $originalArray contains elements of the top index 0 of your sample data, you will need to use $originalArray[0] with the structure you posted. The resulting $newArray will have item_id as keys, if you need a numerically indexed array just use array_values($newArray) at the end.