从2D数组中获取所有组合键码

时间:2013-01-08 15:07:14

标签: php arrays multidimensional-array

我想得到一个数组的组合键 - 这里是例子:

$keys = array(
        array(
            'original',
            'section 1',
            'section 2'
        ),
        array(
            'original',
            'section 1'
        ),
        array(
            'original',
            'section 1'
        ),
        array(
            'original',
            'section 1',
            'section 2'
        ),
        array(
            'original',
            'section 1'
        )
);

所有原始部分都是00000(因为有5个不同的数组,因此可以有5个数字,但是可以有1到n个数组,不限于5个),变量#15将是例如01010.我基本上想得到一个列表列表中的所有变体都带有该键以获取它们。我们假设每个数组中不超过9个部分+原始数据。

输出应如下所示:

array(
    array(
        "key" => "00000",
        "data" => array(
            "original", "original", "original", "original", "original"
        )
    ),
    array(
        "key" => "10000",
        "data" => array(
            "section 1", "original", "original", "original", "original"
        )
    ),
    array(
        "key" => "20000",
        "data" => array(
            "section 2", "original", "original", "original", "original"
        )
    ),
    array(
        "key" => "01000",
        "data" => array(
            "original", "section 1", "original", "original", "original"
        )
    )
    [...]
)  

除此之外,还有一个很好的方法来获得另一种方式。给出关键字01010并让所有部分都回来。

谢谢!

1 个答案:

答案 0 :(得分:2)

以下是我的想法:

$options = array();
$counter1 = 0;
foreach($keys as $values) {
    $counter1++;
    $counter2 = 0;
    $options[$counter1] = array();
    foreach($values as $key => $value) {
        if(isset($options[($counter1 - 1)])) {
            foreach($options[($counter1 - 1)] as $old_val) {
                $counter2++;
                $old_array = $old_val['data'];
                array_push($old_array, $value);
                $options[$counter1][$counter2] = array();
                $options[$counter1][$counter2]['key'] = $old_val['key'] . $key;
                $options[$counter1][$counter2]['data'] = $old_array;
            }
        }
        else {
            $counter2++;
            $options[$counter1][$counter2] = array();
            $options[$counter1][$counter2]['key'] = $key;
            $options[$counter1][$counter2]['data'] = array($value);
        }
    }
}
$all_options = end($options);

你得到72个结果是正确的,因为它是3 * 2 * 2 * 3 * 2 = 72