如何检查两个不同数组中的字符串是否匹配

时间:2015-05-12 00:54:47

标签: php arrays string-matching

我想检查两个不同数组中的字符串$value是否匹配。如果他们匹配,做一些事情。如果不匹配,请做点什么。

以下是单独获取字符串值的代码,但我希望尽可能将它们组合在一起然后比较字符串以进行匹配。

这是第一次查找

        $count = count($cert['tbsCertificate']['subject']['rdnSequence']);
        $exists = array('utf8String', 'printableString', 'teletexString', 'bmpString', 'universalString', 'ia5String');
        $oid = array('id-at-commonName');
        for($i = 0; $i < $count; $i++) {
            foreach($exists as $field) {
                if(
                    array_key_exists($field, $cert['tbsCertificate']['subject']['rdnSequence'][$i][0]['value']) &&
                    in_array($cert['tbsCertificate']['subject']['rdnSequence'][$i][0]['type'], $oid)
                ) {
                    $value = $cert['tbsCertificate']['subject']['rdnSequence'][$i][0]['value'][$field];
                    echo $value;
                    break; // stop further looping
                }
            }
        }

这是第二次查找:

        $count = count($cert['tbsCertificate']['issuer']['rdnSequence']);
        $exists = array('utf8String', 'printableString', 'teletexString', 'bmpString', 'universalString', 'ia5String');
        $oid = array('id-at-commonName');
        for($i = 0; $i < $count; $i++) {
            foreach($exists as $field) {
                if(
                    array_key_exists($field, $cert['tbsCertificate']['issuer']['rdnSequence'][$i][0]['value']) &&
                    in_array($cert['tbsCertificate']['issuer']['rdnSequence'][$i][0]['type'], $oid)
                ) {
                    $value = $cert['tbsCertificate']['issuer']['rdnSequence'][$i][0]['value'][$field];
                    echo $value;
                    break; // stop further looping
                }
            }
        }

1 个答案:

答案 0 :(得分:1)

将查找代码放在以类型作为参数的函数中,并返回找到的值。然后比较两个电话。

function lookup($cert, $type) {
    $count = count($cert['tbsCertificate'][$type]['rdnSequence']);
    $exists = array('utf8String', 'printableString', 'teletexString', 'bmpString', 'universalString', 'ia5String');
    $oid = array('id-at-commonName');
    for($i = 0; $i < $count; $i++) {
        foreach($exists as $field) {
            if(
                array_key_exists($field, $cert['tbsCertificate'][$type]['rdnSequence'][$i][0]['value']) &&
                in_array($cert['tbsCertificate'][$type]['rdnSequence'][$i][0]['type'], $oid)
            ) {
                $value = $cert['tbsCertificate'][$type]['rdnSequence'][$i][0]['value'][$field];
                return $value;
            }
        }
    }
    return null;
}

if (lookup($cert, 'subject') == lookup($cert, 'issuer')) {
    // do something
}