假设我们有类似下面的数组。
[
{
"years": [1, 2, 5],
"value": 1
},
{
"years": [1, 2, 5],
"value": 2
},
{
"years": [1, 2, 5],
"value": 5
}
]
ArrScore (定义):如果数组包含一个包含所有元素的数组 得到一分。所以在这种情况下,$ arr00的总分是9.因为它 包括所有其他9个阵列。 $ arr09的得分为0。
实际情况
目标是按 ArrScore 订购数组。我们需要ArrScores。该方法应该是什么? (理论上或实践上)
答案 0 :(得分:1)
如果我理解正确,这可能会有所帮助:
function compare($a,$b) {
if(count(array_intersect($a, $b)) == count($a)) return -1;
else return 1;
}
$arr0 = [0,2,4,7];
$arr1 = [7,0,2,9,4];
$arr2 = [4,2];
$arr = [$arr0,$arr1,$arr2];
usort($arr,"compare");
foreach($arr as $a) {
print_r($a);
}
打印:
数组([0] => 4 [1] => 2)数组([0] => 0 [1] => 2 [2] => 4 [3] => 7 )数组([0] => 7 [1] => 0 [2] => 2 [3] => 9 [4] => 4)
编辑: 计算每个阵列的ArrayScore:
$arr0 = [0,2,4,7];
$arr1 = [7,0,2,9,4];
$arr2 = [4,2];
$arr = [$arr0,$arr1,$arr2];
$arrayScores = [];
//initialize the Scores with 0
foreach($arr as $a){
$arrayScores[] = 0;
}
//run through all arrays
for($i=0;$i<count($arr);$i++){
//with $j=$i+1, every combination is only checked once
for($j=$i+1; $j<count($arr);$j++){
if(count(array_intersect($arr[$j], $arr[$i])) == count($arr[$j])) {
$arrayScores[$i]++;
}
if(count(array_intersect($arr[$i], $arr[$j])) == count($arr[$i])){
$arrayScores[$j]++;
}
}
}