我在确定如何返回最佳独特匹配时遇到一些困难,同时尽可能多地分配。
场景:每个孩子都有一份最喜欢的水果列表和个人得分。我们每个水果只有一个,所以我们想把它给予最喜欢的孩子。如果有人得分较高,可以没有水果,但我们仍然希望尽可能多地发出水果。
预期结果将是:
0 = [1] Apple
1 = [0] Mango
2 = [0] Banana
3 = null
这是我的输入数组:
Array
(
[0] => Array
(
[0] => Array
(
[name] => Banana
[score] => 80.2
)
[1] => Array
(
[name] => Apple
[score] => 40
)
)
[1] => Array
(
[0] => Array
(
[name] => Mango
[score] => 70
)
[1] => Array
(
[name] => Banana
[score] => 40
)
)
[2] => Array
(
[0] => Array
(
[name] => Banana
[score] => 90
)
[1] => Array
(
[name] => Orange
[score] => 20
)
)
[3] => Array
(
[0] => Array
(
[name] => Mango
[score] => 60
)
)
)
答案 0 :(得分:1)
我的方法首先将您的输入展平为一个简单的2D数组,允许所有行按score
排序,同时保留fruit
和childid
数据。排序后,所有行都会被迭代(而不是进行迭代的全数组搜索),并且只根据请求为每个子项存储最喜欢的水果(如果有的话)。
OP的输入:
$input=[
[['name'=>'Banana','score'=>80.2],['name'=>'Apple','score'=>40]],
[['name'=>'Mango','score'=>70],['name'=>'Banana','score'=>40]],
[['name'=>'Banana','score'=>90],['name'=>'Orange','score'=>20]],
[['name'=>'Mango','score'=>60]]
];
方法:
$result=array_fill_keys(array_keys($input),null); // list all child ids and default to null
// flatten input array for simple sorting and iteration
foreach($input as $i=>$subarrays){
foreach($subarrays as $a){
$restructured[]=['score'=>$a['score'],'fruit'=>$a['name'],'childid'=>$i];
}
}
rsort($restructured); // will sort the array by score DESC
foreach($restructured as $a){
if(is_null($result[$a['childid']]) && !in_array($a['fruit'],$result)){
// only "fruitless" children wanting what is available
$result[$a['childid']]=$a['fruit'];
}
}
var_export($result);
输出:
array (
0 => 'Apple',
1 => 'Mango',
2 => 'Banana',
3 => NULL,
)