A
A
ak_wi2019-07-23 23:15:45
PHP
ak_wi, 2019-07-23 23:15:45

How to get all unique pairs from an array?

There is an array containing arrays with strings inside. For example:

$array = [
    ['Синий', 'Алый', 'Коричневый'],
    ['Дерево', 'Сталь', 'Железо'],
    ['Корабль', 'Самолет', 'Поезд'],
...
];

How to get all unique combinations of values ​​from arrays inside it?
For example: Blue - Tree - Ship, Blue - Tree - Airplane, etc.
I think it is clear that pairs inside arrays are not needed, such as blue-scarlet - a tree, etc.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
0
0xD34F, 2019-07-24
@ak_wi

$numArr = count($array);
$numElems = count($array[0]);

$combinations = [];
$numCombinations = pow($numElems, $numArr);

for ($i = 0; $i < $numCombinations; $i++) {
  $combination = [];

  for ($j = 0; $j < $numArr; $j++) {
    $arrIndex = $j;
    $elIndex = $i / pow($numElems, $j) % $numElems;
    $combination[] = $array[$arrIndex][$elIndex];
  }

  $combinations[] = $combination;
}

O
oleg_ods, 2019-07-23
@oleg_ods

Divide into three arrays, each of which has 1 characteristic (color, material, transport), and then use 3 nested loops to form a string.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question