3

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

1 Answer 1

1

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 )
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.