-2

我需要为这个数组绘制一个堆积条形图,它应该有 2 个条形图,间隔为 2 年(从年19982000

问题:第一条应该是这样的,

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

条形应该合并较短的年份,就像它在2000array02008取自时所做的那样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
)
4

1 回答 1

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.
}
于 2012-08-30T12:45:07.060 回答