所以我在接受采访时提出了一个问题:它说的是:在所有条件下找到平均得分最高的轮胎,如果轮胎在任何情况下的得分都低于5,那么它就会被取消资格。
tf.gather(input, index)
输出显示:注意: C:\ xampp中的数组到字符串转换... Array是得分最好的轮胎:7.3333333333333
问题是如何显示名称' RainForest'而不是'数组'
谢谢
答案 0 :(得分:1)
你有令人困惑的名字,修复它们:
$tires=[
'Desert'=>array('dry'=>10, 'wet'=>4, 'snow'=>1),
'Ocean'=>array('dry'=>6, 'wet'=>8, 'snow'=>6),
'RainForest'=>array('dry'=>6, 'wet'=>10, 'snow'=>6),
'Glacier'=>array('dry'=>4, 'wet'=>9, 'snow'=>10),
'Prairie'=>array('dry'=>7, 'wet'=>7, 'snow'=>7),
];
$max=0;
foreach($tires as $tire => $conditions){ // note key and value
$total=0;
foreach($conditions as $condition => $score){ // note array name
if($score>5){
$total=$total+$score;
}else{
$total=-150000;
}
}
$total=$total/3;
if($total>$max){
$max=$total;
$bestTire = $tire; // note key name
}
}
echo $bestTire." is the best tire with the score: ".$max;
答案 1 :(得分:1)
试试这个:
$minimumScore = 5;
// remove tires that have a single rating less than minimum
$filtered = array_filter($tires, function (array $data) use ($minimumScore) {
return min($data) >= $minimumScore;
});
// calculate scores as average of score per category
$scores = array_map(function (array $data) {
return array_sum($data) / count($data);
}, $filtered);
// find maximum of scores
$bestScore = max($scores);
// find keys with the best score
$bestTires = array_keys($scores, $bestScore);
// there could be more than one tire with same score, pick the first
$bestTire = array_shift($bestTires);
echo sprintf(
'%s is the best tire with the score: %s',
$bestTire,
$bestScore
);
供参考,见:
有关示例,请参阅:
答案 2 :(得分:-2)
您应该了解foreach()
的工作原理。
foreach($tires as $key => $value) {
// $key is your tire name
// $value is the array of data for that tire
}