与值从另一个阵列替换一个数组的钥匙 [英] Replace keys of an array with Value from another array

查看:128
本文介绍了与值从另一个阵列替换一个数组的钥匙的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有象下面这样阵列结构

I have an array structure like below

Array
(
    [1] => Dept1
    [2] => Dept2
    [3] => Dept3
)

和我有另一个数组如下

Array
(
    [1] => Array
        (
            [user1] => 58
            [user3] => 75
        )

    [2] => Array
        (
            [user6] => 162
        )

    [3] => Array
        (
            [user7] => 2
            [user8] => 126
            [user9] => 148

        )
)

我想

Array
    (
        [Dept1] => Array
            (
                [user1] => 58
                [user3] => 75
            )

        [Dept2] => Array
            (
                [user6] => 162
            )

        [Dept3] => Array
            (
                [user7] => 2
                [user8] => 126
                [user9] => 148

            )
    )

在第2个数组中的数字是该部门的数字。和它们的值是第一个阵列中的present。我想用从第一阵列值第二个数组的部门编号。

The numbers in 2nd array are the department numbers. And their values are present in the first array. I want to replace the department number in second array with value from first array.

我曾尝试与 array_replace(),但没有得到成功的。

I have tried with array_replace() but don't get successful.

请帮忙

在此先感谢

推荐答案

如果第二个数组有比你查找数组更少的元件,或者如果键不以相同的顺序,你需要将键值首先映射,然后结合阵列使用 array_combine()

If the second array has less elements than your lookup array or if the keys are not in the same order, you need to map the key values first and then combine the arrays using array_combine().

array_combine(array_map(function($key) use ($depts) {
    return $depts[$key]; // translate key to name
}, array_keys($dept_values)), $dept_values));

否则,您可以立即将它们组合起来:

Otherwise, you can combine them immediately:

array_combine($depts, $dept_values);

另请参阅: array_map()

这篇关于与值从另一个阵列替换一个数组的钥匙的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆