2017-07-26 72 views
0

所以我在採訪中遇到了一個問題,它說的是這樣的:在所有條件下找到平均得分最高的輪胎,並且如果輪胎得分較低在任何情況下都不得超過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

的問題是,我該怎麼辦到節目的名字「熱帶雨林」,而不是「數組」

謝謝

+0

你的算法通常可以使用的改善;看看我的答案。 – localheinz

回答

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; 
+0

謝謝,先生! :) –

+0

這麼多的蘇聯方法。 – jcorry

+0

你拼寫錯*輪胎*。 – localheinz

-1

您應該閱讀有關foreach()如何工作。

foreach($tires as $key => $value) { 
    // $key is your tire name 
    // $value is the array of data for that tire 
} 
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 
); 

僅供參考,請參閱:

有關示例,請參見:

相關問題