0

I have a payment function that emails me whenever a transaction occurs, the issue is it emails me too much data, and not all of it is relevant. The payment itself is processed by Authorize API (which is also whats returning this data).

function sent_mail($data = array()) {
    $out = "";
    foreach ($data as $k => $value) {
        if (is_array($value)) {
            foreach ($value as $key => $v) {
                $out .= ucwords($key) . ' Name : ' . $v . "<br/>";
            }
        } else {
            $out .= ucwords($k) . ' : ' . $value . "<br/>";
        }
    }
    $msg = "<h2><strong>Receipt Of Payment</strong></h2>" . "<br/><br/>";
    $msg .= "$out";

    $to = '[email protected]';
    $subject = 'New Payment';
    $headers = "MIME-Version: 1.0\r\n";
    $headers .= "Content-Type: text/html; charset=iso-8859-1\n";
    @mail($to, $subject, $msg, $headers);
}

The email I get, includes these fields:

DataValue, DataDescriptor, InvoiceID, Amount, Item_name, Item_Desc, FirstName, LastName, Email, Website, Country, Zip, Terms, TransID, Card_Holder

Where as, the only data I need is

InvoiceID, Amount, Item_name, FirstName, LastName, Email, Website

I've not sure how to limit this, create a skip?

1
  • 1
    If the fields that you want to filter by are keys in $data then you have a slew of functions for filtering $datafor the foreach(): array_diff*(), array_udiff*(), array_intersect*() and array_uintersect*(). But the goal is like a variation of Sumurai8's answer, you either whitelist or blacklist to limit the array to the keys that you want in the email. Commented Feb 10, 2022 at 23:52

1 Answer 1

1

In a loop you can use the continue statement to immediately go to the next iteration of that loop. That means you can create a condition to skip over the loop that adds data to your email if the key does not match one of the keys you want to include.

if (!in_array($k, ['InvoiceID', 'Amount', 'Item_name', 'FirstName', 'LastName', 'Email', 'Website'])) {
  continue;
}
Sign up to request clarification or add additional context in comments.

3 Comments

I've tried this three different ways but keep getting empty emails, can you send the full function. Maybe I'm doing something wrong. This looks like a good idea (though I would think it would be without !). Thank you!
Your loop handles both nested arrays and ucwords, so your actual keynames might differ a little bit. I would suggest normalising $data so you do not need the extra loop foreach ($value as $key => $v) {. You can use var_dump to figure out which keys you actually have and adjust the whitelisted keys that way.
I got it working, thank you!

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.