Avatar of erzoolander
erzoolander
 asked on

PHP Array Grouping of Values

I have an array like this...

$array = array();
$array['2017-03-15']['rate']=125;
$array['2017-03-16']['rate']=125;
$array['2017-03-17']['rate']=130;
$array['2017-03-18']['rate']=130;
$array['2017-03-19']['rate']=125;
$array['2017-03-20']['rate']=125;
$array['2017-03-21']['rate']=115;

I need the output to be like.

"2 days @ 125
2 days @ 130
2 day at $125
1 Day at $115"

in the order of the days.

So, if there's X consecutive days at a specific amount, it just needs to group those together as a single line reflecting that - in date order.

How would I go about pulling that off?
PHP

Avatar of undefined
Last Comment
erzoolander

8/22/2022 - Mon
ASKER CERTIFIED SOLUTION
gr8gonzo

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
erzoolander

ASKER
the approach makes sense to me - but the output seems to be off.

Here's my code -

$array = array();
$array['2017-03-15']['rate']=125;
$array['2017-03-16']['rate']=125;
$array['2017-03-17']['rate']=130;
$array['2017-03-18']['rate']=130;
$array['2017-03-19']['rate']=130;
$array['2017-03-20']['rate']=135;
?>
<pre>
<?php print_r($array);?>
</pre>
<?php


$current_rate = null;
$current_rate_count = 0;
$rate_log = array();

foreach($array as $day => $day_details)
{
  $day_rate = $day_details["rate"];

  if($day_rate == $current_rate)
  {
    $current_rate_count++;
  }
  else
  {
    if($current_rate !== null)
    {
      $rate_log[] = array($current_rate_count,$current_rate);
    }

    // Update the current rate to the new one
    $current_rate = $day_rate;
    $current_rate_count = 1;
  }
}

foreach($rate_log as $log_details)
{
  echo $log_details[0] . " day at \$" . $log_details[1] . "<br />\n";
} ]

Open in new window


which outputs:

2 day at $125
3 day at $130

-- for some reason it's omitting the 135 value...or anything that comes after 130.
gr8gonzo

Sorry, I was missing a line. After the foreach loop through $array, you might still have some data at the end that needs to be added to the $rate_log array, so just check and add it after the loop ends:

if($current_rate_count > 0) { $rate_log[] = array($current_rate_count,$current_rate); }
erzoolander

ASKER
Thanks!  I found that after also :)

Thank you!
I started with Experts Exchange in 2004 and it's been a mainstay of my professional computing life since. It helped me launch a career as a programmer / Oracle data analyst
William Peck