MrSo
MrSo

Reputation: 640

Php replace array keys with another array keys if key exists

I have this array :

Array (amounts)
(
    [0] => Array
        (
            [0] => 95
            [1] => 2
        )

    [1] => Array
        (
            [0] => 96
            [1] => 5
        )

)

And this

Array (invoices)
(
    [1] => 
    [2] => 490
    [3] => 
    [4] => 
    [5] => 1400
)

This is what I am trying to get :

Array
(
    [1] => 
    [95] => 490 // Id found in Amounts array so replaced id by Key '0'
    [3] => 
    [4] => 
    [96] => 1400 // Id found in Amounts array so replaced id by Key '0'
)

I have tried to deal with the answser found here but without success.

$newamounts = array_combine(array_map(function($key) use ($invoices) {
    return $invoices[$key]; // translate key to name
}, array_keys($invoices)), $amounts);

Any help greatly appreciated. Thx

Upvotes: 3

Views: 1787

Answers (1)

Rizier123
Rizier123

Reputation: 59701

This should work for you:

(Here i go through each innerArray of $amounts with a foreach loop and then i check if the array element in $invoices with the index 1 of the innerArray is not empty and if not i set the new element with the key and value and unset the old one)

<?php

    $amounts = array(
                    array(
                            95,
                            2
                        ),
                    array(
                            96,
                            5
                        )
            );

    $invoices = array(1 =>"", 2 => 490, 3 => "", 4 => "", 5 => 1500);

    foreach($amounts as $innerArray) {

        if(!empty($invoices[$innerArray[1]])) {
            $invoices[$innerArray[0]] = $invoices[$innerArray[1]];
            unset($invoices[$innerArray[1]]);
        }
    }

    print_r($invoices);

?>

Output:

Array ( [1] => [3] => [4] => [95] => 490 [96] => 1500 )

Upvotes: 1

Related Questions