0

I have the following array:

$array = array
(
    'firstname' => array('Daniel', 'John'),
    'lastname' => array('Smith', 'Larsson')
);

I want to turn it into:

$array = array('firstname=daniel:lastname=smith', 
'firstname=daniel:lastname=larsson', 
'firstname=john:lastname=smith',
'firstname=john:lastname=larsson');

Of course the array can have more names and also have more fields other than "firstname" and "lastname".

What would be the most optimal way to solve this?

mickmackusa
  • 43,625
  • 12
  • 83
  • 136
Daniele Testa
  • 1,538
  • 3
  • 16
  • 34
  • A recursive function should be the optimal way, since you are practically using the same pattern all over the array ([link](http://stackoverflow.com/questions/2648968/what-is-a-recursive-function-in-php)). – Masiorama Jan 12 '15 at 08:35

1 Answers1

1

Something like the following should work:

function combine($fields) {
    if (!count($fields)) return array('');

    $values = reset($fields);
    $field = key($fields);

    array_shift($fields);
    $suffixes = combine($fields);

    $options = array();
    foreach ($values as $value) {
        $options = array_merge($options, array_map(function($suffix) use($field, $value) {
            return "$field=$value:$suffix";
        }, $suffixes));
    }

    return $options;
}

You will probably have to adjust it though (like remove extra : in the end).

Cthulhu
  • 1,379
  • 1
  • 13
  • 25