Search code examples
phparraysmergecombinationsdelimited

Merge combinations of values from a 2d array and form non-standard delimited strings


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?


Solution

  • 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).