[英]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"]
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.
如果找到,则将其复制到结果中, 并在找到的位置擦除第二个数组中的匹配值,因此无法再次匹配。
foreach ($a as $x) { ... }
: $x is a value from the first array foreach ($a as $x) { ... }
: $ x是第一个数组中的值 $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
false
if ($i !== false) {
: if the search was successful... if ($i !== false) {
:如果搜索成功...
$c[] = $x;
: then add the value to the result array $c and... unset($b[$i]);
: ...remove it from the found position in $b . return $c;
: return the result array to the caller
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.