当密钥未知时,如何找到关联数组的第一个/第二个元素?

时间:2010-10-29 07:35:50

标签: 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;
}

3 个答案:

答案 0 :(得分:11)

使用这些函数设置内部数组指针:

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);之类的操作。

答案 1 :(得分:4)

$array = array('Alpha' => 1.1,'Bravo' => 2.2,'Charlie' => 3.3,'Delta' => 4.4,'Echo' =>5.5, 'Golf' => 6.6);

$pos = 3;

function getAtPos($tmpArray,$pos) {
 return array_splice($tmpArray,$pos-1,1);
}

$return = getAtPos($array,$pos);

var_dump($return);

OR

$array = array('Alpha' => 1.1,'Bravo' => 2.2,'Charlie' => 3.3,'Delta' => 4.4,'Echo' =>5.5, 'Golf' => 6.6);

$pos = 3;

function getAtPos($tmpArray,$pos) {
    $keys = array_keys($tmpArray);
    return array($keys[$pos-1] => $tmpArray[$keys[$pos-1]]);
}

$return = getAtPos($array,$pos);

var_dump($return);

修改

假设第一个元素的$ pos = 1,但通过将函数中的$ pos-1引用更改为$ pos

,可以轻松更改$ pos = 0

答案 2 :(得分:0)

您可以使用 array_keys,具体取决于您的阵列有多大。

echo $groups[( array_keys( $groups )[1] )];