D
D
danforth2017-05-04 15:49:55
PHP
danforth, 2017-05-04 15:49:55

How to make a combination of values ​​from two arrays?

There is such an array:

$features = array(
3 => array(
      1 => 1,
      2 => 1,
      3 => 1,
    ),
    5 => array(
      815 => 1,
      816 => 1,
      817 => 1,
    ),
);

do not pay attention to the unit as a value.
The output should be an array of key combinations of all arrays, namely:
3:1;5:815;
3:1;5:816;
3:1;5:817;
3:2;5:815;
3:2;5:816;
3:2;5:817;
3:3;5:815;
3:3;5:816;
3:3;5:817;

First, we glue the key and one of the value keys through a colon, at the end we concatenate with a semicolon.
In principle, the order itself is unimportant, the main thing is not to swap 3 and 5.
Upd : if there is only one array in the initial $features array, then we make a combination of its keys like this:
3:1;
3:2;
3:3;

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Maxim Khodyrev, 2017-05-04
@danforth

// рекурсивно создать варианты для каждого корневого ключа
function create_variants($arr)
{
    $items = [];
    foreach ($arr as $key => $value) {
        $vars = [$key];
        if (!is_array($value)) {
            $items[] = implode(';', $vars);
            continue;
        }

        $variants = create_variants($value);
        foreach ($variants as $variantValue) {
            $items[] = implode(';', array_merge($vars, [$variantValue]));
        }
    }

    return $items;
}

/**
 * объединить варианты корневых ключей
 * @param $partsCount количество объединяемых в одно вариантов
 */
function join_variants($items, $partsCount)
{
    $result = [];
    $joinable = array_chunk($items, ceil(count($items)/$partsCount));

    foreach ($joinable as $chunk) {
        foreach ($chunk as $index => $item) {
            if (isset($result[$index])) {
                $result[$index] .= ';'.$item;
            } else {
                $result[$index] = $item;
            }
        }
    }

    return array_map(function ($v) {
        return $v.';';
    }, $result);
}

var_dump(join_variants(
    create_variants($features),
    count($features)
));

A
Andrew, 2017-05-04
@OLS

Recursion(0,"")
function Recursion(Level, String)
If Level>number_arrays, then return the current value of the string
otherwise loop through the number of elements in the array:
- Recursion(Level+1, String+";"+"array_name" +":"+"element_value")

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question