phpの閉パケットによる再帰

13376 ワード

eg
既知文字列の配列値変換対応するキー値文字列既知配列キー値変換配列値文字列

function getBrandEmailList(){
	return [
		1=>[
		    'index'=>1,
            'name' => 'test1',
            'email' => '[email protected]'
        ],
		2=>[
		    'index'=>2,
            'name' => 'test2',
            'email' => '[email protected]'
        ],
		3=>[
		    'index'=>3,
            'name' => 'test3',
            'email' => '[email protected]'
        ],
	];
}

function getBrandEmails($ks = []){
	$val = $ks;
    $fns = function (&$i,&$str) use (&$fns,&$val){
        if ($i < count($val) ) {
        	$k =  $val[$i];
            $str .= getBrandEmailList()[$k]['email'].',';
            $i++;
            $fns($i, $str);
        }

        return $str;
    };
    return rtrim($fns($i=0,$str=''),',');
}


function getBrandKey($emails=''){
	if (empty($emails)) {
		return false;
	} else {
		$emailArray = array_filter( explode(',', $emails) );
		$emailArrFlip = array_flip( array_column(getBrandEmailList(),'email', 'index') );
        $fns = function (&$i,&$str) use (&$fns,&$emailArrFlip,&$emailArray){
            if ($i < count($emailArray) ) {
                $k =  $emailArray[$i];
                $str .= $emailArrFlip[$k].',';
                $i++;
                $fns($i, $str);
            }
            return $str;
        };

        return rtrim($fns($i=0,$str=''),',');
	}