2010-10-29 56 views
4

在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; 
} 

回答

10

使用這些函數來設置內部數組指針:

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

當然,我可以做$ groupNames = array_keys($ groups),然後我有$ groupNames [0]和$ groupNames [1],謝謝。 – 2010-10-29 07:54:34

+0

@愛德華是啊,我在這方面太過分了。 – joni 2010-10-29 08:14:46

3
$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); 

EDIT

假定$ POS = 1表示第一個元件,但容易通過在改變$ POS-1的引用改變爲$ POS = 0 $ pos

相關問題