仅当数组元素中存在某个键时才复合数组

问题描述

在laravel中,我有一个工作代码块,在其中循环数组,并在其中调用电子邮件列表。但是,数组中的某些元素具有要添加的特定电子邮件。因此,无论如何我总是希望使用现有的电子邮件配置列表,但是如果此人的array元素具有电子邮件密钥,那么我想将其添加到emails数组中,如果有道理。

以下是现有代码

    $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”块中。我该如何正确地执行此操作,以便仅某些数组元素具有电子邮件密钥,如果我将它们添加到始终使用配置列表的电子邮件数组中?

解决方法

如评论中所述,您可以使用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' => []
]