如何建立递归函数列出了多层次阵列的所有组合? [英] How to build recursive function to list all combinations of a multi-level array?

查看:119
本文介绍了如何建立递归函数列出了多层次阵列的所有组合?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个可以包含任意数量的元素的数组。每个元素都包含一个ID叫选项(也有任意数量的元素)的数组。这里是结构:

I have an array that can contain any number of elements. Each element contains an ID and an array called "options" (also with any number of elements). Here is the structure:

$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字段+一个选项数组值,并且该值是下一个元素的阵列,再下,等等。基本上,它应该给我上述阵列的每个组合(有点像一棵树),顺序,数组的定义:

I'd like to create another array based off of this one. Each key is the ID field + an 'option' array value, and the value is an array of the next element, and then the next, and so on. Basically it should give me every combination of the above arrays (sort of like a tree), in the order that the array was defined:

$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')
                            )
             );

由于数组可以包含任意数量的元素,我假设我需要包括某种类型的递归函数。我没有在递归太多的经验,所以这是一个pretty艰巨的任务给我。

Because the array can contain any number of elements, I'm assuming I would need to include some type of recursive function. I don't have much experience in recursion, so this is a pretty daunting task for me.

我能得到在何处建设这个递归函数启动一些指点?

Could I get some pointers on where to start in building this recursive function?

推荐答案

怎么样了呢?当然那里面有一个bug,但其在正确的方向前进......

Hows this ? Sure there's a bug in there, but its going in the right direction ....

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

这篇关于如何建立递归函数列出了多层次阵列的所有组合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆