Venorize Posted November 9, 2011 Share Posted November 9, 2011 I have an XML document that id decrypted and shown onto a table. At the bottom of the page, I'm trying to have it count up one foreach($Data as $Types) // loop through book foreach($Types as $Colors) // loop through book { print_r(count($Colors->Color)); } There are 4 colors, blue, green, red, yellow. Blue is listed 7 times, green is 3, red is 8, and yellow is 4 times. What I expect it to print is: 7 3 8 4 Instead, it's printing this: 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 If I was to just do the print function without count, it lists like this: blue red blue red green yellow blue red yellow red red green yellow yellow blue blue green blue yellow blue red red blue red My end-goal of this code is to get it to print this: Blue: 7 Green: 3 Red: 8 Yellow: 4 Quote Link to comment Share on other sites More sharing options...
PFMaBiSmAd Posted November 9, 2011 Share Posted November 9, 2011 You would use an array, with the key being the color name, to count each occurrence in the data - <?php $counts = array(); // initialize before the start of your loops ... // inside the loop - if(isset($counts[$Colors->Color])){ $counts[$Colors->Color]++; } else { $counts[$Colors->Color] = 1; } Quote Link to comment Share on other sites More sharing options...
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.