Johnny2 Posted March 30, 2013 Report Posted March 30, 2013 (edited) I have this multidimensional array which I'll name "original": $original= array 0 => array 'animal' => 'cats' 'quantity' => 1 1 => array 'animal' => 'dogs' 'quantity' => '1' 2 => array 'animal' => 'cats' 'quantity' => '3' However, I want to merge internal arrays with the same animal to produce this new array: $new= array 0 => array 'animal' => 'cats' 'quantity' => 4 1 => array 'animal' => 'dogs' 'quantity' => '1' I've been trying for hours, but can't figure it out. I've tried the following code, but get "Fatal error: Unsupported operand types" (Referring to line 11). 1 $new = array(); 2 foreach($original as $entity) 3 { 4 if(!isset($new[$entity["animal"]])) 5 { 6 $new[$entity["animal"]] = array( 7 "animal" => $entity["animal"], 8 "quantity" => 0, 9 ); 10 } 11 $new[$entity["animal"]] += $entity["quantity"]; 12 } So, I don't know what I'm doing and I could really use some help from the experts. Edited March 30, 2013 by Johnny2 Quote
falkencreative Posted March 30, 2013 Report Posted March 30, 2013 (edited) Here's a fixed version: <?php $original = array( array('animal' => 'cats', 'quantity' => '1'), array('animal' => 'dogs', 'quantity' => '1'), array('animal' => 'cats', 'quantity' => '3') ); $new = array(); foreach($original as $entity) { if(!isset($new[$entity["animal"]])) { $new[$entity["animal"]] = array("animal" => $entity["animal"], "quantity" => 0); } $new[$entity["animal"]]['quantity'] += $entity["quantity"]; } echo "<pre>"; print_r($new); echo "</pre>"; Basically, the key thing was this line: $new[$entity["animal"]]['quantity'] += $entity["quantity"]; In your original sample, you missed the "['quantity]" portion, meaning you were trying to access the entire array, not specifically the quantity key within that array. This meant you were trying to add a number to an array, and since those are incompatible types, you got an error. However... this code doesn't do exactly what you want, since this is the result: Array ( [cats] => Array ( [animal] => cats [quantity] => 4 ) [dogs] => Array ( [animal] => dogs [quantity] => 1 ) ) Note how you have "[cats]" and "[dogs]" instead of [0] and [1]? You'll need to work on fixing that, but it's a first step in the right direction. Edited March 30, 2013 by Ben Quote
Johnny2 Posted April 2, 2013 Author Report Posted April 2, 2013 Thank you very much Ben! The fixed worked well. I figured out the rest from there. Sorry it took so long to respond. I believe I got distracted when I last read your feedback. Quote
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.