S
S
Sergey Erzhovich2021-11-29 16:11:34
PHP
Sergey Erzhovich, 2021-11-29 16:11:34

How to generate a list with many conditions?

We need a function that takes parameters:

function generator($pattern, $conditions) {
    ...
}

It is used like this:

generator('http://site.com/{lang}/{category}/page/{page}', [
    'category' => 'other',
    'lang' => ['en', 'ru'],
    'page' => [1, 2],
]);

The output should be:

http://site.com/en/other/page/1
http://site.com/en/other/page/2
http://site.com/ru/other/page/1
http://site.com/ru/other/page/2

Answer the question

In order to leave comments, you need to log in

2 answer(s)
0
0xD34F, 2021-11-29
@Drilled-prog

function generator($str, $params) {
  $result = [];

  if (count($params)) {
    $key = key($params);
    $values = is_array($params[$key]) ? $params[$key] : [ $params[$key] ];
    unset($params[$key]);

    foreach ($values as $val) {
      array_push($result, ...generator(str_replace("{{$key}}", $val, $str), $params));
    }
  } else {
    $result[] = $str;
  }

  return $result;
}

C
Carburn, 2021-12-02
@Carburn

Solution without recursion

function generator($str, $params) {
    $result = [$str];

    foreach ($params as $key => $param) {
        $values = is_array($params[$key]) ? $params[$key] : [$params[$key]];
        $copy = unserialize(serialize($result));
        
        foreach ($values as $val) {
            foreach ($result as &$oneResult) {
                $oneResult = str_replace(sprintf("{%s}", $key), $val, $oneResult);
            }
            if ($val != end($values)) {
                $result = array_merge($copy, $result);
            }
        }
    }

    return $result;
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question