简体   繁体   English

在PHP中合并二维数组中的值

[英]Merge values in 2 dimensional array in PHP

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? 解决此问题的最佳方法是什么?

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). 您可能要调整,虽然它(如删除多余的:到底)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM