我有一个数组,我想只返回数组的最低值,但无论我尝试什么,我得到错误或我得到完整的列表。帮助
function myForEachLoop()
$StudentPopulation = array('BSU'=>19664, 'CSU'=>25500, 'SDSU'=>35887, 'UHM'=>20000,
'AFA'=>4000, 'UNLV'=>28000, 'FS'=>21389, 'UNR'=>17000, 'UNM'=>25767, 'UW'=>13476);
ksort($StudentPopulation);
foreach($StudentPopulation as $aSchool => $aPop)
{
$output .= '<strong>School:</strong> ' . ($aSchool) . '<strong> Population:</strong> ' . $aPop . '<br />';
}
return $output;
我想回归“学校:AFA”人口:4000“。
答案 0 :(得分:1)
这个问题几乎没有任何意义,但如果你真的需要这样做,请尝试:
function myForEachLoop(&$StudentPopulation) {
ksort($StudentPopulation);
$min = 'NO_MIN';
foreach($StudentPopulation as $aSchool => $aPop)
{
if($min=='NO_MIN' || $aPop<$min) {
$output = '<strong>School:</strong> ' . ($aSchool) . '<strong> Population:</strong> ' . $aPop . '<br />';
$min = $aPop;
}
}
return $output;
}
$StudentPopulation = array('BSU'=>19664, 'CSU'=>25500, 'SDSU'=>35887, 'UHM'=>20000,
'AFA'=>4000, 'UNLV'=>28000, 'FS'=>21389, 'UNR'=>17000, 'UNM'=>25767, 'UW'=>13476);
echo myForEachLoop($StudentPopulation);
答案 1 :(得分:0)
试试这个:
function myForEachLoop()
{
$StudentPopulation = array('BSU'=>19664, 'CSU'=>25500, 'SDSU'=>35887, 'UHM'=>20000,
'AFA'=>4000, 'UNLV'=>28000, 'FS'=>21389, 'UNR'=>17000, 'UNM'=>25767, 'UW'=>13476);
ksort($StudentPopulation);
$lowestValue = min($studentPopulation); // 4000
$lowestValueIndex = array_keys($studentPopulation, min($studentPopulation)); // AFA
$output .= '<strong>School:</strong> ' . ($lowestValueIndex) . '<strong> Population:</strong> ' . $lowestValue. '<br />'
return $output;
}