亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

僅當數組元素中存在某個鍵時才復合數組

僅當數組元素中存在某個鍵時才復合數組

PHP
慕婉清6462132 2023-09-22 16:54:48
在 Laravel 中,我有一個工作代碼塊,我在其中循環一個數組,并在其中調用一個電子郵件列表。但是,數組中的某些元素具有我想要添加到其中的特定電子郵件。因此,無論如何,我總是希望使用現有的電子郵件配置列表,但如果該人的數組元素有電子郵件密鑰,我想將其添加到電子郵件數組中(如果這有意義的話)。這是現有的代碼:    $items = array(        array(            "employee" => 123,            "name" => "Tom",            "email" => "[email protected]"        ),        array(            "employee" => 234,            "name" => "Sally"        ),        array(            "employee" => 345,            "name" => "Rob"        ),        array(            "employee" => 456,            "name" => "Ed"            "email" => "[email protected]"        ),        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' => [ "[email protected]", "[email protected]" ],

 'cc' => []

]


查看完整回答
反對 回復 2023-09-22
  • 1 回答
  • 0 關注
  • 88 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號