I
I
Igor Mavlikhanov2018-09-02 22:39:22
PHP
Igor Mavlikhanov, 2018-09-02 22:39:22

Where do you need to start building an algorithm for generating urls from an array?

There is an array:

$urlFragments = [
    'pozdravlenya',
    'na-angliyskom',
    [ 'lubimoy', 'lubimomu' ],
    'v-proze',
    [ 'korotkie', 'nekorotkie' ]
  ];

And I need to create different links from it:

Array
(
    [0] => pozdravlenya/na-angliyskom/lubimoy/v-proze/korotkie
    [1] => pozdravlenya/na-angliyskom/lubimoy/v-proze/nekorotkie
    [2] => pozdravlenya/na-angliyskom/lubimomu/v-proze/korotkie
    [3] => pozdravlenya/na-angliyskom/lubimomu/v-proze/nekorotkie
)

I can't figure out how to do the recursion correctly.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2018-09-02
@Gori4ka

function getUrls($parts, $acc = '') {
  $urls = [];

  if (count($parts)) {
    $part = array_shift($parts);
    if (!is_array($part)) {
      $part = [ $part ];
    }

    foreach ($part as $p) {
      array_push($urls, ...getUrls($parts, ($acc ? $acc.'/' : '').$p));
    }
  } else {
    $urls[] = $acc;
  }

  return $urls;
}


$urls = getUrls($urlFragments);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question