查找具有间隙的数组中的总年份跨度

时间:2012-08-30 12:31:58

标签: php arrays bar-chart

我需要为此数组绘制一个堆积条形图,该条形图应该有2个条形图,每隔2年跨越一个空格(从1998年到2000

问题: 第一个栏应该是,

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

这些小节应合并较短的年度跨度,就像从2000 array02008 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}}

1 个答案:

答案 0 :(得分:0)

如果两个数组项根据某些条件相邻并且在某些其他字段上具有某些相等条件,则需要合并它们。

您可以这样做:

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