将php数组中的所有值与其他值进行比较
问题描述:
我有一个php数组
如何比较此数组的所有值并根据自定义逻辑(可能是回调函数)过滤掉值.
How can I compare all values of this array and filter out values based on custom logic (callback function maybe).
本质上,我想将每个数组值与数组中的每个其他值进行比较,并基于一些自定义逻辑,保留该值或将其从数组中删除
Essentially, I want to compare each array value with every other value within the array and based on some custom logic, either keep the value or remove it from the array
谢谢
答
可能您必须手动进行:
function your_callback($a, $b)
{
return $a != $b;
}
$array = array(/** Your array here... **/);
$n = count($array);
$filtered = array();
for($i = 0; $i < $n; $i++)
{
$ok = true;
for($j = 0; $j < $n; $j++)
{
if($j != $i && !your_callback($array[$i], $array[$j])
{
$ok = false;
break;
}
}
if($ok)
array_push($filtered, $array[$i]);
}
unset($array);
$array = $filtered;
例如,此示例将过滤数组的唯一值;例如:更改your_callback定义以实现其他逻辑.
This example will filter unique values of array for example; change your_callback definition to implement other logic.