array_combine()合并常用项

时间:2014-07-21 04:55:39

标签: php arrays

我希望每个项目都为key=>value,并且不希望使用array_combine()合并/组合公共项目。

我想在key=>value中组合foreach返回值,这是结果

foreach ($users_in_groups as $get_uid)
{
    $uid[] = $get_uid->user_id;
    $gnm[] = $get_uid->name;
}

$uid

的结果
Array
(
    [0] => 2
    [1] => 3
    [2] => 1
    [3] => 1
    [4] => 1
    [5] => 1
)

$gnm

的结果
Array
(
    [0] => member
    [1] => member
    [2] => system_admin
    [3] => admin
    [4] => TRA
    [5] => member
)

合并为key=>value

array_combine($uid, $gnm);

以下是结果

Array
(
    [2] => member
    [3] => member
    [1] => member
)

这不是我想要的。

我想如下

Array
(
    [2] => member
    [3] => member
    [1] => system_admin
    [1] => admin
    [1] => TRA
    [1] => member
)

请注意用户ID是关键,而不是像当前结果那样合并。

1 个答案:

答案 0 :(得分:2)

在PHP中,每个数组键必须是唯一的。这不是一个有效的PHP数组,因为它有多个相同的键(1的多个实例作为键):

Array
(
    [2] => member
    [3] => member
    [1] => system_admin
    [1] => admin
    [1] => TRA
    [1] => member
)

您可以通过手动创建具有多个相同键的数组来测试:

$c = array(
    1 => 'a',
    3 => 'b',
    3 => 'c',
);
print_r($c);

在PHP 5.5中,这导致:

Array
(
    [1] => a
    [3] => c
)

你应该瞄准的是(根据你的需要)这样的数组:

array(
    2 => array('member'),
    3 => array('member'),
    1 => array('system_admin', 'admin', 'TRA', 'member'),
);

如果您需要,可以使用以下内容:

$uid = array(2, 3, 1, 1, 1, 1);
$gnm = array('member', 'member', 'system_admin', 'admin', 'TRA', 'member');
$result = array();
foreach($uid as $k => $u) {
    if (!isset($result[$u])) {
        $result[$u] = array();
    }
    $result[$u][] = $gnm[$k];
}
print_r($result);