عثمان غني
عثمان غني

Reputation: 2708

Replace keys of an array with Value from another array

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

Upvotes: 0

Views: 270

Answers (3)

Ja͢ck
Ja͢ck

Reputation: 173562

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

Upvotes: 4

Nono
Nono

Reputation: 7302

This code is working as expected for me:

PHP Code:

<?php
print_r(array_combine($firstArray, $secondArray));
?>

Array Output:

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

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

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

)

Upvotes: -1

Hari Das
Hari Das

Reputation: 10864

Try this. Basically join and explode will do your work.

<html>
<head>
<title>Copy to new array</title>
</head>
<body>
<?php
$dept= array('Dept1', 'Dept2', 'Dept3', 'Dept4');
$temp= join(",",$dept);
$department=explode(",",$temp);
echo "The first element in new array is: " . $department[0];
echo " and the second element in new array is: " . $department[1];
?>
</body>
</html>

Upvotes: -1

Related Questions