PHP搜索数组中的数组

时间:2015-09-03 02:05:43

标签: php arrays

我有一个例如

的数组
 $name1 = "this is a string";
 $name2 = "another string";
 $arr1 = str_split($name1); //will return an array
 $arr2 = str_split($name2); //will return an array

现在我想要的是摆脱从$ arr1到$ arr2的所有相同的字母并计算剩余的数字。 示例输出:

oe //total count is 2

2 个答案:

答案 0 :(得分:0)

你可以这样做,

$name1 = "this is a string";
$name2 = "another string";
$arr1 = str_split($name1); //will return an array
$arr2 = str_split($name2); //will return an array
$uniquecounts = array_count_values(array_merge($arr1, $arr2));
foreach($uniquecounts as $char => $count) {
    if($count == 1) {
        echo $char . ' is unique' . "\n";
    }
}

这将您的两个个性化字符数组合在一起,并仅比较一次出现的字符。请查看手册,了解将来如何使用array_count_valueshttp://php.net/manual/en/function.array-count-values.php

输出:

o is unique
e is unique

<强>更新

<?php
$name1 = "this is a string";
$name2 = "another string";
$arr1 = str_split($name1); //will return an array
$arr2 = str_split($name2); //will return an array
$uniquecounts = array_count_values(array_merge($arr1, $arr2));
$unqiues = '';
foreach($uniquecounts as $char => $count) {
    if($count == 1) {
        $unqiues .=  $char;
    }
}
echo $unqiues . ' ' . strlen($unqiues);

输出:

oe 2

答案 1 :(得分:0)

function deduce($string1, $string2) {

    $result = array();

    foreach (count_chars($string2 . $string1, 1) as $i => $val) {
        if($val == 1) {
            $result[] = chr($i);
        }
    }

    return $result;
}

我之前遇到过这个,我做的就是这个。