Find total year spans in an array with gaps

僤鯓⒐⒋嵵緔 提交于 2019-12-13 09:09:13

问题


I need to draw a stacked bar graph for this array which should have 2 bars separated with a white-space of 2 years span (from year 1998 to 2000)

The Problem: the first bar should be like,

*1998-1997* - *2 years gap*  - *2000-2008* 

The bars should merge shorter year-spans within like it did in taking 2000 from array0 and 2008 from array 1

Array
(
    [comp_name] => C++
    [parent_cat_name] => Information Technology
    [sub_cat_name] => Programming
    [total_years] => 6
    [last_year] => 2006
    [start_year] => 2000
)

Array
(
    [comp_name] => .NET
    [parent_cat_name] => Information Technology
    [sub_cat_name] => Programming
    [total_years] => 7
    [last_year] => 2008
    [start_year] => 2001
)

Array
(
    [comp_name] => API
    [parent_cat_name] => Information Technology
    [sub_cat_name] => Programming
    [total_years] => 1
    [last_year] => 1998
    [start_year] => 1997
)

回答1:


You want to merge two array items, if they are adjacent according to some condition AND have some equality condition on some other fields.

You might do:

for(;;)
{
    $merge = array();
    $n     = count($data);
    for ($i = 0; empty($merge) && $i < $n-1; $i++)
    {
        for ($j = $i+1; empty($merge) &&  $j < $n; $j++)
        {
            // Are $i and $j congruent?
            if ($data[$i]['parent_cat_name'] != $data[$j]['parent_cat_name'])
               continue;
            if ($data[$i]['sub_cat_name'] != $data[$j]['sub_cat_name'])
               continue;

            // Are $i and $j adjacent?
            if ($data[$i]['last_year']+1 == $data[$j]['start_year'])
            {
                $merge = array($i, $j);
                break;
            }
            if ($data[$j]['last_year']+1 == $data[$i]['start_year'])
                $merge = array($j, $i);
                break;
            }
            // They are congruent but not adjacent, try the next
        }
    }
    // If we get to the end and find nothing mergeable, exit.
    if (empty($merge))
        break;
    list($i, $j) = $merge;
    // We add $j to $i
    $data[$i]['last_year'] = $data[$j]['last_year']
    $data[$i]['total_years'] += $data[$j]['total_years']
    // We destroy $j
    unset($data[$j]);
    // Dirty renumber
    $data = array_values($data);
    // Now data has been modified, let's do this again.
}


来源:https://stackoverflow.com/questions/12196910/find-total-year-spans-in-an-array-with-gaps

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!