Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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
)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
266 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...