在PHP,當你有一個關聯數組,例如:如何在密鑰未知時查找關聯數組的第一個/第二個元素?
$groups['paragraph'] = 3
$groups['line'] = 3
什麼是訪問數組的第一個或第二個元素,當你不知道鍵的值的語法?
是否有一個C#LINQ聲明類似,你可以說:
$mostFrequentGroup = $groups->first()?
或
$mostFrequentGroup = $groups->getElementWithIndex(0)?
還是我必須使用一個foreach語句,並挑選出來,因爲我在做此代碼示例的底部:
//should return "paragraph"
echo getMostFrequentlyOccurringItem(array('line', 'paragraph', 'paragraph'));
//should return "line"
echo getMostFrequentlyOccurringItem(array('wholeNumber', 'date', 'date', 'line', 'line', 'line'));
//should return null
echo getMostFrequentlyOccurringItem(array('wholeNumber', 'wholeNumber', 'paragraph', 'paragraph'));
//should return "wholeNumber"
echo getMostFrequentlyOccurringItem(array('wholeNumber', '', '', ''));
function getMostFrequentlyOccurringItem($items) {
//catch invalid entry
if($items == null) {
return null;
}
if(count($items) == 0) {
return null;
}
//sort
$groups = array_count_values($items);
arsort($groups);
//if there was a tie, then return null
if($groups[0] == $groups[1]) { //******** HOW TO DO THIS? ***********
return null;
}
//get most frequent
$mostFrequentGroup = '';
foreach($groups as $group => $numberOfTimesOccurrred) {
if(trim($group) != '') {
$mostFrequentGroup = $group;
break;
}
}
return $mostFrequentGroup;
}
當然,我可以做$ groupNames = array_keys($ groups),然後我有$ groupNames [0]和$ groupNames [1],謝謝。 – 2010-10-29 07:54:34
@愛德華是啊,我在這方面太過分了。 – joni 2010-10-29 08:14:46