【问题标题】:Find total year spans in an array with gaps在有间隙的数组中查找总年份跨度
【发布时间】:2012-08-30 12:31:58
【问题描述】:

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

问题: 第一个栏应该是,

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

条形应该合并较短的年份,就像从array02008 中提取2000 和从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
)

【问题讨论】:

  • 那么条形图代码在哪里?
  • 条形图编码不是问题,但要找到年份间隔是
  • 您能否发布您的绘图脚本,以便我们了解您在绘图时的实际意思?这似乎很不清楚。
  • 从上面的数组中,我们能看到我们有多少不同的年份跨度吗?例如,我们在上面的数组中有 2 个,一个是 2000 到 2008,因为它们都在彼此的位置,另一个是 1997 到 1998

标签: php arrays bar-chart


【解决方案1】:

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

你可以这样做:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-06-18
    • 1970-01-01
    • 2022-10-13
    • 1970-01-01
    • 2016-04-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多