基于排列生成密钥的最优算法

时间:2011-09-19 15:06:41

标签: php algorithm permutation nested-loops

在我的应用程序中,我从UI表单中获得的参数很少(zone_id,startdate,enddate,brand,model)。这些参数中的每一个都是包含一个或多个参数的数组。

我的表单参数如下所示:

Array
(
[sel_date_option] => today
[startdate] => 2011-09-19
[enddate] => 2011-09-19
[zone_id] => 1576,1562,1561
[model] => Array
    (
        [0] => A300
    )

[brand] => Array
    (
        [0] => ACTS
    )

)

现在,我想生成这些参数组合的键。他们会是这样的:

[zone_id]_[model]_[brand]_[model]_[startdate]_[enddate]

这反映了上述值的所有可能安排。 对于上述输入,我应该得到以下键:

1576_ACTS_A300_2011-09-19
1562_ACTS_A300_2011-09-19
1561_ACTS_A300_2011-09-19

在给出相同的startdate和enddate之前,也可以进入2011-09-19至2011-09-21之类的时期。

我正在做的是我在所有参数数组中使用嵌套循环,然后创建一个复杂的数组数组,如下所示:

Array
(
[0] => Array
    (
        [0] => 1576_DZ_A300
    )

[1] => Array
    (
        [0] => 1576_DZ_A300
        [1] => 1562_DZ_A300
    )

[2] => Array
    (
        [0] => 1576_DZ_A300
        [1] => 1562_DZ_A300
        [2] => 1561_DZ_A300
    )

[3] => Array
    (
        [0] => 1576_DZ_A300
        [1] => 1562_DZ_A300
        [2] => 1561_DZ_A300
        [3] => 1563_DZ_A300
    )
 )

我正在做的是首先创建一个包含所有区域的数组:

Array
(
[0] => 1576
[1] => 1562
[2] => 1561
[3] => 1563
)

然后我使用嵌套循环为所有可能的模型和品牌数组循环它:

function getInventoryData($criteria)
{

    $index = "";

    if($criteria['zone_id']!='')
    {
        $zone = explode(',', $criteria['zone_id']);
        for($i=0;$i<count($zone);$i++)
        {
            $index[] .= $zone[$i];
        }

        echo '<pre>';print_r($index);exit;
    }

    if(!empty($criteria['model']))
    {
        foreach($index as $key=>$value)
        {
            foreach($criteria['model'] as $model)
            {
                $temparr[] = $index[$key].'_'.$model;
            }
            $index[$key] = $temparr;
        }

    }

现在,有没有其他有效的方法来实现这一目标?

此外,还有另一个与上述方法相关的开销:

在读取生成的密钥时,我必须循环遍历所有级别,并且在大量数据的情况下,复杂性可能确​​实是一个问题。

1 个答案:

答案 0 :(得分:0)

如果我理解你正在尝试做什么,这是我能做到的最有效的方法:

function getInventoryData ($arr) {
  // Make sure all required keys are set
  if (!isset($arr['zone_id'],$arr['model'],$arr['brand'],$arr['startdate'],$arr['enddate'])) return FALSE;
  // Make a date string for the end of the keys
  $dateStr = $arr['startdate'].(($arr['startdate'] == $arr['enddate']) ? '' : '_'.$arr['enddate']);
  // Normalise the data
  if (!count($arr['zone_id'] = array_unique(explode(',',$arr['zone_id']))) || !count($arr['brand'] = array_unique($arr['brand'])) || !count($arr['model'] = array_unique($arr['model']))) return FALSE;
  // Get all possible permutations
  $result = array();
  foreach ($arr['zone_id'] as $zone) foreach ($arr['brand'] as $brand) foreach ($arr['model'] as $model) $result[] = "{$zone}_{$brand}_{$model}_{$dateStr}";
  // Return the result
  return $result;
}
相关问题