How to generate in PHP all combinations of items in multiple arrays

前端 未结 8 886
野性不改
野性不改 2020-11-22 07:20

I\'im trying to find all combinations of items in several arrays. The number of arrays is random (this can be 2, 3, 4, 5...). The number of elements in each array is random

8条回答
  •  一个人的身影
    2020-11-22 07:39

    This code besides simplicity, get all combinations of multiple arrays and preserves keys.

    function get_combinations($arrays) {
        $result = array(array());
        foreach ($arrays as $property => $property_values) {
            $tmp = array();
            foreach ($result as $result_item) {
                foreach ($property_values as $property_key => $property_value) {
                    $tmp[] = $result_item + array($property_key => $property_value);
                }
            }
            $result = $tmp;
        }
        return $result;
    }
    

    Exemple:

    Array
    (
        Array
        (
            '1' => 'White',
            '2' => 'Green',
            '3' => 'Blue'
        ),
        Array
        (
            '4' =>' Small',
            '5' => 'Big'
        )
    )
    

    Will return:

    Array
    (
        [0] => Array
        (
            [1] => White
            [4] =>  Small
        )
        [1] => Array
        (
            [1] => White
            [5] => Big
        )
        [2] => Array
        (
            [2] => Green
            [4] =>  Small
        )
        [3] => Array
        (
            [2] => Green
            [5] => Big
        )
        [4] => Array
        (
            [3] => Blue
            [4] =>  Small
        )
        [5] => Array
        (
            [3] => Blue
            [5] => Big
        )
    )
    

提交回复
热议问题