0

I have 2 arrays:

first array of total transactions (haystack):

[0] => Array (
    [transaction_id] => 62369600431
    [invoice_number] => 37161
    )
[1] => Array (
    [transaction_id] => 62369595048
    [invoice_number] => 37346
    )
[2] => Array (
    [transaction_id] => 62369537530
    [invoice_number] => 38064
    )

Second array of select orders (needle):

[0] => Array (
    [invoice_number] => 37161
    )
[1] => Array (
    [invoice_number] => 37346
    )

My goal is to create a third array that finds all transaction_id from the first array that have a match of order_id from the second.

I have tried array_merge and array_intersect both unsuccessfully (because I don't fully understand how to use them obviously.)

Sackling
  • 1,780
  • 5
  • 37
  • 71

1 Answers1

2

You might use array_filter and get all the invoice_numbers to check for using example array_column.

Then in the filter, check if the number occurs in the invoice_numbers using in_array.

$array1 = [
    [
        "transaction_id" => 62369600431,
        "invoice_number" => 37161
    ],
    [
        "transaction_id" => 62369595048,
        "invoice_number" => 37346
    ],
    [
        "transaction_id" => 62369600431,
        "invoice_number" => 38064
    ]
];

$array2 = [
    [
        "invoice_number" => 37161
    ],
    [
        "invoice_number" => 37346
    ]
];

$invoiceNumbers = array_column($array2, "invoice_number");
$result = array_filter($array1, function($x) use ($invoiceNumbers) {
   return in_array($x["invoice_number"], $invoiceNumbers);
});

print_r($result);

Output

Array
(
    [0] => Array
        (
            [transaction_id] => 62369600431
            [invoice_number] => 37161
        )

    [1] => Array
        (
            [transaction_id] => 62369595048
            [invoice_number] => 37346
        )

)

Php demo

The fourth bird
  • 154,723
  • 16
  • 55
  • 70
  • Thanks this works great. Can you explain to me the portion of the callback in array_filter. I am not really understanding the function($x) use ($invoiceNumbers). – Sackling May 24 '20 at 18:48
  • array_filter iterates over all the values in the array and passes each value to the callback. To use in_array, the callback needs the array with invoice numbers and that is where `use` is for. This page can be helpful explaining how that works – The fourth bird May 24 '20 at 19:08
  • https://stackoverflow.com/questions/1065188/in-php-what-is-a-closure-and-why-does-it-use-the-use-identifier – The fourth bird May 24 '20 at 19:09