How do I combine consecutive month names in php?

I have an array like:

Array ( [0] => Jan [1] => Feb [2] => Mar [3] => Apr [4] => May [5] => Jun [6] => Sep [7] => Oct [8] => Dec ) 

I need to convert it to

 Array ( [0] => "Jan - Jun" [1] => "Sep - Oct" [2] => "Dec" ) 

Months will always be alright, but since the array is dynamic, I can't think of a good effective way of doing this, except converting each month to a number with date_parse, and then combine with the months around it! but i'm really confused how to do this, any ideas?

+4
source share
2 answers

How about something like this:

 function findConsecutiveMonths(array $input) { // Utility list of all months static $months = array('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'); $chunks = array(); for ($i = 0; $i < 12; $i++) { // Wait until the $i-th month is contained in the array if (!in_array($months[$i], $input)) { continue; } // Find first consecutive month that is NOT contained in the array for ($j = $i + 1; $j < 12; $j++) { if (!in_array($months[$j], $input)) { break; } } // Chunk is from month $i to month $j - 1 $chunks[] = ($i == $j - 1) ? $months[$i] : $months[$i] .' - '. $months[$j - 1]; // We know that month $j is not contained in the array so we can set $i // to $j - the search for the next chunk is then continued with month // $j + 1 because $i is incremented after the following line $i = $j; } return $chunks; } 

Demo: http://codepad.viper-7.com/UfaNfH

+1
source

This should do it:

 function combine_months($months) { $all_months = array("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"); $target = array(); $start = null; for ($i = 0; $i<12; $i++) { if (!in_array($all_months[$i], $months) && $start != null) { if ($start == null) { $target[] = $all_months[$i-1]; } else { $target[] = sprintf("%s - %s", $start, $all_months[$i-1]); } $start = null; } elseif ($start == null) { $start = $all_months[$i]; } } if ($start != null) { $target[] = $start; } return $target; } $test = combine_months(array("Jan","Feb","Mar","Apr","May","Jun","Sep","Oct","Dec")); var_dump($test); 

Iterates over all available months, recalling the first common month, adding to the target array when there is not enough month.

0
source

Source: https://habr.com/ru/post/1491117/


All Articles