php - 当键未知时如何找到关联数组的第一个/第二个元素?

标签 php arrays associative-array

在 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/

相关文章:

java - Java 中的 RSA 加密,PHP 中的解密

php - 具有 Symfony 3/Doctrine 属性形式的一对多对一

javascript - 如何在javascript中从数组中获取键

java - 如何将 6 个整数数组与二维整数数组 [19][5] 进行比较?

php - 使用 foreach 向关联数组添加一个值?

actionscript-3 - ActionScript - 比较和删除复杂数组的重复项?

php - 未找到类 'JFactory'

php - 如何设置自定义 laravel 资源 Controller 请求 url

ios - 将数组保存为核心数据中的数据的正确方法是什么?

javascript - 在javascript中创建动态关联数组