代码之家  ›  专栏  ›  技术社区  ›  Edward Tanguay

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

  •  6
  • Edward Tanguay  · 技术社区  · 14 年前

    在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;
    }
    
    2 回复  |  直到 14 年前
        1
  •  11
  •   joni    14 年前

    使用以下函数设置内部数组指针:

    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); .

        2
  •  4
  •   Mark Baker    14 年前
    $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);
    

    或者

    $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