2009-07-25 11 views
1

私は任意の数の要素を含むことができる配列を持っています。各要素には、IDと「options」という配列(任意の数の要素を含む)が含まれています。構造は次のとおりです。マルチレベル配列のすべての組み合わせをリストする再帰関数を作成するにはどうすればよいですか?

$arr = array(
      array('id' => 10, 'options' => array(3, 5)), 
      array('id' => 15, 'options' => array(2, 4, 8, 9)), 
      array('id' => 20, 'options' => array(2, 6, 7)), 
      // ... any number of elements 
      ); 

私はこれに基づいて別の配列を作成したいと思います。各キーはIDフィールド+オプションの配列値で、値は次の要素の配列、次に次の要素の配列などです。基本的にそれは私に(ソートの木のように)上記の配列の全ての組み合わせを与える必要があり、配列が定義されている順に:

$new = array(
      '10-3' => array(
          '15-2' => array('20-2', '20-6', '20-7'), 
          '15-4' => array('20-2', '20-6', '20-7'), 
          '15-8' => array('20-2', '20-6', '20-7'), 
          '15-9' => array('20-2', '20-6', '20-7') 
          ), 
      '10-5' => array(
          '15-2' => array('20-2', '20-6', '20-7'), 
          '15-4' => array('20-2', '20-6', '20-7'), 
          '15-8' => array('20-2', '20-6', '20-7'), 
          '15-9' => array('20-2', '20-6', '20-7') 
          ) 
      ); 

配列は、任意の数の要素を含めることができるため、私は私を想定していますいくつかの種類の再帰関数を含める必要があります。私は再帰で多くの経験を持っていないので、これは私にとってかなり困難な作業です。

この再帰関数の作成を開始する場所について、いくつかの参考にしてください。

答えて

1

これは?確かにそこにはバグがありますが、その私はPHP 1を提供することはできません

function possibilities ($input) { 
    $output=array(); 
    $current = array_shift($input); 
    foreach ($current as #key=>$value) { 
    if empty($input) { 
     $output[] = $key.'-'.$value; 
    } else { 
     $output[$key.'-'.$value] = possibilities($input); 
    } 
    } 
    return $output; 
} 
+0

ベンさんありがとう、本当にありがとう!それは私に必要なものについて私に良いアイデアを与えます。私はそれを試し、あなたに知らせるでしょう。 –

+0

あなたの例のロジックはかなり完璧でした。再度、感謝します! –

0

....右方向に行くのが、Pythonの1:

arr = [ (10, [3,5]), 
     (15, [2,4,8,9]), 
     (20, [2,6,7]) ] 

def combine_options(pair): 
    id, options = pair 
    res = [] 
    for i in options: 
     res.append("%d-%d" % (id, i)) 
    return res 

def combine(arr, i): 
    res = {} 
    if i == len(arr)-1: 
     return combine_options(arr[i]) 
    for elem in combine_options(arr[i]): 
     res[elem] = combine(arr, i+1) 
    return res 

import pprint 
pprint.pprint(combine(arr,0)) 

これは

を与えます
{'10-3': {'15-2': ['20-2', '20-6', '20-7'], 
      '15-4': ['20-2', '20-6', '20-7'], 
      '15-8': ['20-2', '20-6', '20-7'], 
      '15-9': ['20-2', '20-6', '20-7']}, 
'10-5': {'15-2': ['20-2', '20-6', '20-7'], 
      '15-4': ['20-2', '20-6', '20-7'], 
      '15-8': ['20-2', '20-6', '20-7'], 
      '15-9': ['20-2', '20-6', '20-7']}} 
+0

Martinさんの広範な例をありがとう!あまりにも悪い私はPythonを知らない:( –

関連する問題