0

I have an array structure like below

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

And I have another Array as below

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

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

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

        )
)

I want

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

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

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

            )
    )

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.

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

Please help

Thanks in advance

1
  • of what type are the DeptXs? You can only use numbers and Strings as keys in an array. Commented Jul 5, 2013 at 7:05

1 Answer 1

4

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);

See also: array_map()

Sign up to request clarification or add additional context in comments.

5 Comments

it is giving error Both parameters should have an equal number of elements.
then any other solution please.
@1------- Update your question with the actual arrays you're working with would be a good start
It is same as actual array. Nothing different just values.
Okay . But I have 10 values in 2nd array and 9 values in first array.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.