0

I have a logical structure or idea of something i want to happen and i wanted it to be coded in PHP using array, here's the scenario:

10 Loops/occurrence of month

month => repetition

jan => 2
mar => 1
sep => 5
dec => 2

As shown above i have a loop that occur 10 times, within that count of loops 4 different month have been recorded, and every specific month there is a chance that is has been repeated multiple times like the month (sep) has been repeated 5times. This idea is same as example a record of a person of what are the months he/she traveled and how many times he traveled within that month from 10 recorded travels. Any idea how to build this in PHP using Arrays? Any suggestions or answers are greatly appreciated!

Ok here's a real deal what i wanted to happen, i pull the records of months from a database, then i wanted to display the months pulled from database and the how many times it has been repeated, example the display are like these:

Jan (2)
Sep (5)

I wanted it to be dynamic, no certain month will be displayed if it doesn't exist from the database record.

3
  • I edit the above question. The output should be like the above. Commented Apr 16, 2012 at 20:00
  • Use array_count_values(). Commented Jan 16 at 0:53
  • Or set up a database query that uses GROUP BY and COUNT() aggregate function calls. This question is Unclear and lacks a minimal reproducible example. Commented Jan 16 at 0:54

1 Answer 1

2

I think he's trying to perform rudimentary frequency analysis. Assuming you have dates fed into an array somehow, you can proceed by using strtotime(), date() functions to generate keys, and then parse them.

First, create some dummy data:

// dummy data; unsure of the format, so going with time()-like structure
$dates = array();
for( $i = 0; $i < 10; $i++ ) {
    $dates[] = strtotime(sprintf("%s-%s-2012", rand(1,30), rand(1,12) ));
}

Now perform a frequency count, keyed by month written by date("M" ...):

$freq = array();
foreach( $dates as $timestamp ) {
    // assuming it's all the same year, discover the month
    $month = date("M", $timestamp );

    if( !isset($freq[$month]) ) $freq[$month] = 0;
    $freq[$month]++;
}

At this point, you'll have something resembling what you want:

print_r( $freq );

Array
(
    [Sep] => 2
    [Feb] => 2
    [Nov] => 1
    [Dec] => 1
    [Jan] => 2
    [Apr] => 1
    [May] => 1
)

If the year varies, you may want to double-joint this somehow, or otherwise.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.