I
I
ItsCoder2018-09-14 02:43:53
PHP
ItsCoder, 2018-09-14 02:43:53

How to collect all possible values ​​from an array?

Good hour!
There is such an array with possible GET parameters:

spoiler
$get_params = array(
    array(
        'color=a1',
        'color=a2',
        'color=a3'
    ),
    array(
        'material=b1',
        'material=b2',
        'material=b3'
    ),
    array(
        'glass=c1',
        'glass=c2',
        'glass=c3'
    )
);

I need to match each array with each other to get all possible link options, for example:
spoiler
site.ru/?color=a1&material=b1&glass=c1
site.ru/?color=a1&material=b1&glass=c2
site.ru/?color=a1&material=b1&glass=c3

site.ru/?color=a1&material=b2&glass=c1
site.ru/?color=a1&material=b2&glass=c2
site.ru/?color=a1&material=b2&glass=c3
...

More simply, then:
Source array
$get_params = array(
    array(
        'a1',
        'a2',
        'a3'
    ),
    array(
        'b1',
        'b2',
        'b3'
    ),
    array(
        'c1',
        'c2',
        'c3'
    )
);
Final version
$get_params = array(
        'a1b1c1',
        'a1b1c2',
        'a1b1c3',
        'a1b2c1',
        'a1b2c2',
        'a1b2c3',
        'a1b3c1',
        'a1b3c2',
        'a1b3c3'
        // ...
);

Does anyone have any ideas how this can be implemented? I so understand here the recursion is necessary?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
I
ItsCoder, 2018-09-14
@ItsCoder

The solution was under our noses:

function combineArray (&$arr, $idx = 0) {
    static $line = array();
    static $keys;
    static $max;
    static $results;
    if ($idx == 0) {
        $keys = array_keys($arr);
        $max = count($arr);
        $results = array();
    }
    if ($idx < $max) {
        $values = $arr[$keys[$idx]];
        foreach ($values as $value) {
            array_push($line, $value);
            combineArray($arr, $idx+1);
            array_pop($line);
        }
    } else {
        $results[] = $line;
    }
    if ($idx == 0) return $results;
}

H
hacker2001, 2018-09-14
@hacker2001

$A = [/* какие-то данные */];
$B = [/* какие-то данные */];
$C = [/* какие-то данные */];
$result = [];
foreach ($A as $a) {
  foreach ($B as $b) {
    foreach ($C as $c) {
      $result[] = $a.$b.$c;
    }
  }
}
echo '<pre>';
var_dump($result);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question