Jump to content

count() issues


Venorize

Recommended Posts

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

Link to comment
Share on other sites

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;	
}

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.