在 Laravel 中,我有一个工作代码块,我在其中循环一个数组,并在其中调用一个电子邮件列表。但是,数组中的某些元素具有我想要添加到其中的特定电子邮件。因此,无论如何,我总是希望使用现有的电子邮件配置列表,但如果该人的数组元素有电子邮件密钥,我想将其添加到电子邮件数组中(如果这有意义的话)。这是现有的代码: $items = array( array( "employee" => 123, "name" => "Tom", "email" => "Tom@sitepoint.com" ), array( "employee" => 234, "name" => "Sally" ), array( "employee" => 345, "name" => "Rob" ), array( "employee" => 456, "name" => "Ed" "email" => "ed@sitepoint.com" ), array( "employee" => 567, "name" => "Barbara" ) ); foreach($items as $item){ //if there is an override email in the command if($this->option('email') != 'default') { if(!filter_var($this->option('email'), FILTER_VALIDATE_EMAIL)) { $this->error('invalid email:'.$this->option('email')); return; } $emails = ['to'=>[$this->option('email')],'cc'=>[]]; } else { //This line works as is but I want a condition so that if the array element has and "email" key, I add that value as well $emails = config('emails.printouts.employeePrintOuts'); //here I would need to add the array value (if email is set in that element) } ... }有问题的部分仅位于“else”块中。我怎样才能正确地做到这一点,以便只有某些数组元素才会有电子邮件密钥,如果它们有,我将其添加到始终使用配置列表的电子邮件数组中?
1 回答
郎朗坤
TA贡献1921条经验 获得超9个赞
正如评论中提到的,您可以使用array_key_exist()函数来检查$items包含email键。
另外,$emails['to']仅在子数组不包含当前子数组的情况下,$items['email']您才可以使用in_array()函数来填充子数组。
解决方案:
if ( array_key_exist('email', $item) && !in_array($item['email'], $emails['to']) )
{
//TODO validate $item['email'] here
$emails['to'][] = $item['email'];
}
//Result $emails array will be looks like this:
[
'to' => [ "Tom@sitepoint.com", "ed@sitepoint.com" ],
'cc' => []
]
- 1 回答
- 0 关注
- 53 浏览
添加回答
举报
0/150
提交
取消