简体   繁体   English

比较数组并计算其值

[英]Comparing arrays and counting their values

How could I compare these arrays and count their values: 我如何比较这些数组并计算其值:

$arrayone = array("3", "2", "1", "2", "3");
$arraytwo = array("1", "2", "3", "2", "1");

My goal isn´t 3 (unique values) or 5 (same amount of values in general) but 4! 我的目标不是3(唯一值)或5(通常是相同数量的值),而是4! The second array contains one 1 too much, how can i get a new array like this: 第二个数组包含一个太多的1,我如何获得这样的新数组:

$arraythree = array("1", "2", "3", "2");

This is giving me 3 unique values: 这给了我3个独特的价值:

$intersect = array_intersect($arrayone, $arraytwo);
$arraythree = array_unique($intersect);
count($arraythree)

This is giving me 5 non-unique values: 这给了我5个非唯一值:

$arraythree = array_intersect($arrayone, $arraytwo);
count($arraythree)

You could use this custom function: 您可以使用以下自定义函数:

function myIntersect($a, $b) {
    foreach ($a as $x) {
        $i = array_search($x, $b);
        if ($i !== false) {
            $c[] = $x;
            unset($b[$i]);
        }
    }
    return $c;
}

How to use: 如何使用:

$arrayone = array("3", "2", "1", "2", "3");
$arraytwo = array("1", "2", "3", "2", "1");
$result = myIntersect($arrayone, $arraytwo);
print_r($result); // ["3", "2", "1", "2"]

Explanations 说明

The idea is to take each value from the first array and find the first position where it occurs in the second. 这个想法是从第一个数组中获取每个值,然后在第二个数组中找到它的第一个位置。 If found, then it is copied into the result, and the matching value in the second array is erased at the found position, so it cannot be matched again. 如果找到,则将其复制到结果中, 在找到的位置擦除第二个数组中的匹配值,因此无法再次匹配。

  1. foreach ($a as $x) { ... } : $x is a value from the first array foreach ($a as $x) { ... }$ x是第一个数组中的值
  2. $i = array_search($x, $b); : $i is the first position where the value occurs in the second array, or if not found, $i is false $ i是值在第二个数组中出现的第一个位置,或者,如果找不到,则$ ifalse
  3. if ($i !== false) { : if the search was successful... if ($i !== false) { :如果搜索成功...
    • $c[] = $x; : then add the value to the result array $c and... :然后将值添加到结果数组$ c中并...
    • unset($b[$i]); : ...remove it from the found position in $b . :...从找到的位置$ b中将其删除。 Note that in PHP the arrays passed to the function are in fact copies of the original arrays, so such removals have no effect on the original arrays that were passed to the function. 请注意,在PHP中,传递给函数的数组实际上是原始数组的副本,因此此类删除对传递给函数的原始数组没有影响。
  4. Repeat previous steps for all values in the first array 对第一个数组中的所有值重复前面的步骤
  5. return $c; : return the result array to the caller :将结果数组返回给调用方

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM