在 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;
}
最佳答案
使用这些函数设置内部数组指针:
http://ch.php.net/manual/en/function.reset.php
http://ch.php.net/manual/en/function.end.php
这是获取实际元素的方法: http://ch.php.net/manual/en/function.current.php
reset($groups);
echo current($groups); //the first one
end($groups);
echo current($groups); //the last one
如果您想拥有最后一个/第一个键,那么只需执行类似$tmp = array_keys($groups);
的操作即可。
关于php - 当键未知时如何找到关联数组的第一个/第二个元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4049914/