如何在另一个阵列中显示数组的名称
问题描述:
所以我在采访中遇到了一个问题,它说的是这样的:在所有条件下找到平均得分最高的轮胎,并且如果轮胎得分较低在任何情况下都不得超过5分。如何在另一个阵列中显示数组的名称
$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 $key){
$total=0;
foreach($key as $condition=>$score){
if($score>5){
$total=$total+$score;
}else{
$total=-150000;
}
}
$total=$total/3;
if($total>$max){
$max=$total;
$bestTire=$key;
}
}
echo $bestTire." is the best tire with the score: ".$max;
输出说:注意:数组字符串转换在C:\ XAMPP ... 阵列与成绩最好的轮胎:7.3333333333333
的问题是,我该怎么办到节目的名字“热带雨林”,而不是“数组”
谢谢
答
你有混淆的名称,解决这些问题:
$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;
答
您应该阅读有关foreach()
如何工作。
foreach($tires as $key => $value) {
// $key is your tire name
// $value is the array of data for that tire
}
答
试试这个:
$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
);
仅供参考,请参阅:
- http://php.net/manual/en/function.array-filter.php
- http://php.net/manual/en/function.array-map.php
- http://php.net/manual/en/function.array-sum.php
- http://php.net/manual/en/function.count.php
- http://php.net/manual/en/function.max.php
- http://php.net/manual/en/function.array-keys.php
- http://php.net/manual/en/function.array-Shift.php
有关示例,请参见:
你的算法通常可以使用的改善;看看我的答案。 – localheinz