在php中将字符串组合成数组

Sam*_*uel 1 php arrays string

我有一个 Web 服务,可以从外部数据库中识别人员及其功能,如果登录成功,该数据库会返回一组数据。数据(我现在感兴趣的)被分成不同的字符串,如下所示:

$groups="group1, group2, group3"
$functions="member, member, admin"
Run Code Online (Sandbox Code Playgroud)

字符串的第一个元素$groups对应于字符串的第一个元素$functions

字符串中可以有空位:

$groups="group1,, group3";
$functions="member,, admin";
Run Code Online (Sandbox Code Playgroud)

将它们结合起来获得的最佳方式是什么:

$usertype(
    group1=>member, 
    group2=>member, 
    group3=>admin,
);
Run Code Online (Sandbox Code Playgroud)

然后我计划使用array_search()来获取与函数对应的组的名称。

Bab*_*aba 5

这是非常棘手的,尤其是当第一个元素为空时,但这是一个全面的解决方案

你需要的是:

// Your Varriables
$groups = "group1,, group3";
$functions = "member,, admin";

// Break Into Array
$groups = explode(",", $groups);
$functions = explode(",", $functions);

// Combine both new Arrays and Output Result
$new = array_combine($groups, $functions);
print_r($new);
Run Code Online (Sandbox Code Playgroud)

如果您需要修复null值,那么:

例子 :

// Your Varriables
$groups = "group1,, group3";
$functions = "member,, admin";

// Break Into Array
$groups = explode(",", $groups);
$functions = explode(",", $functions);

// Fix Null Values
$groups = fixNull($groups, true);
$functions = fixNull($functions);

// Combine both new Arrays and Output Result
$new = array_combine($groups, $functions);
print_r($new);
Run Code Online (Sandbox Code Playgroud)

输出

Array
(
    [group1] => member
    [group2] => member
    [group3] => admin
)
Run Code Online (Sandbox Code Playgroud)

查看现场演示

更复杂:

// Your Varriables
$groups = ",,, group3";
$functions = ",member,, admin";

// Fix Null Values
$groups = fixNull(explode(",", $groups), true);
$functions = fixNull(explode(",", $functions));

// Combine both new Arrays and Output Result
$new = array_combine($groups, $functions);
print_r($new);
Run Code Online (Sandbox Code Playgroud)

输出

Array
(
    [group4] => member
    [group5] => member
    [group6] => member
    [group3] => admin
)
Run Code Online (Sandbox Code Playgroud)

现场演示

使用的功能

function fixNull($array, $inc = false) {
    $ci = new CachingIterator(new ArrayIterator($array), CachingIterator::FULL_CACHE);
    if ($inc) {
        $next = array_filter($array);
        $next = current($next);
        $next ++;
    } else {
        $next = array_filter($array);
        sort($next);
        $next = end($next);
    }

    $next || $next = null;
    $modified = array();

    foreach($ci as $item) {
        $modified[] = empty($item) ? trim($next) : trim($item);
        if (! $ci->getInnerIterator()->current()) {
            $item || $item = $next;
            $next = $inc ? ++ $item : $item;
        }
    }
    return $modified;
}
Run Code Online (Sandbox Code Playgroud)