从数组中获取数据并组合使用PHP发送电子邮件

时间:2016-02-26 11:22:50

标签: php arrays loops email associative-array

我的代码是:

$itemArray = array();
    foreach ($a->getDetails() as $b) {
        if ($b->getValue1() !== $b->getValue2()) {
            if (!array_key_exists($b->getId(), $itemArray)) {
                $itemArray[$b->getId()] = array('name' => $b->getName(), 'age' => $b->getAge());
        }
    }
}
if (count($itemArray) > 0 && $b->getValue1() !== $b->getValue2()) {
    foreach($itemArray as $item) {
        $personName = $item['name'];
        $personAge  = $item['age'] ;
        $content    = ('Name is: ' . $personName . ', age is: ' . $personAge);
    }
}

    $emailAddress = 'emailaddress@gmail.com';
    $fromEmail    = 'noreply@gmail.com';

    $body = <<<EOF
Here is an example email:

$content
EOF;

    $mail = new sfMail();
    $mail->setBody($body);
    $mail->send();

现在邮件只输出一个条目,例如:

Name is: Bob, age is: 20.

但我希望电子邮件在$b->getValue1() !== $b->getValue2()之类的时候输出数组的所有条目:

Name is: Bob, age is 20:
Name is: John, age is 30.

如何设置我的内容变量,以便从数组中抓取所有内容并在电子邮件中很好地输出?

谢谢!

2 个答案:

答案 0 :(得分:2)

只需附加 $ content :)

$content = '';
if (count($itemArray) > 0 && $b->getValue1() !== $b->getValue2()) {
    foreach($itemArray as $item) {
        $personName  = $item['name'];
        $personAge   = $item['age'] ;
        $content    .= ('Name is: ' . $personName . ', age is: ' . $personAge) . "\n";
    }
}
// ... mail setting ...
$body = $content;

答案 1 :(得分:1)

只需使用。=而不是=

此处为$ content。=(&#39;名称为:&#39;。$ personName。&#39;,年龄为:&#39;。$ personAge);

$content = "";
if (count($itemArray) > 0 && $b->getValue1() !== $b->getValue2()) {
    foreach($itemArray as $item) {
        $personName = $item['name'];
        $personAge  = $item['age'] ;
        $content    .= ('Name is: ' . $personName . ', age is: ' . $personAge);
    }
}