Answer the question
In order to leave comments, you need to log in
How to generate a list with many conditions?
We need a function that takes parameters:
function generator($pattern, $conditions) {
...
}
generator('http://site.com/{lang}/{category}/page/{page}', [
'category' => 'other',
'lang' => ['en', 'ru'],
'page' => [1, 2],
]);
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
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;
}
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 questionAsk a Question
731 491 924 answers to any question