2015-03-31 184 views
0

我有以下代码返回值的索引位置,其中的键与函数($ haystack)的参数中提供的值相匹配。相同位置的重复值在PHP数组中重复使用foreach循环

$results = array("098"=>90,"099"=>89,"100"=>77,"101"=>77); 

function getPosition($results,$StudentID){ 
    arsort($results); 

    $index = 1; 
    $exists = ''; 
    $keys = array_keys($results); 

    foreach($keys as $key) 
    { 
     if($key == $StudentID) 
     { 
     $score = $results[$key]; 
     $position = $index; 
     } 
     $index++; 
    } 
    return $position; 

} 
echo getPosition($results,"098").'<br />'; 
echo getPosition($results,"099").'<br />'; 
echo getPosition($results,"100").'<br />'; 
echo getPosition($results,"101").'<br />'; 

结果如下所列:

  • 90 = 1
  • 89 = 2
  • 77 = 4
  • 77 = 3

现在我的问题是: 1.我不知道如何让函数返回两个相同的位置相似的值(例如, 77);

编辑:函数中的StudentID参数是数组值的关键。 例如。 098是数组中的一个键,它的值为一个特定的StudentID。

回答

0

简单的返回位置为数组。

$results = array("098"=>90,"099"=>89,"100"=>77,"101"=>77); 

function getPosition($results,$StudentID) 
{ 
arsort($results); 

$index = 1; 
$exists = ''; 
$keys = array_keys($results); 
$position = array(); 

foreach($keys as $key) 
{ 
    if($key == $StudentID) 
    { 
    $score = $results[$key]; 
    $position[] = $index; 
    } 
    $index++; 
} 
return $position; 

} 

print_r(getPosition($results,"77")); 
0

你应该寻找值而不是键?

$results = array("098"=>90,"099"=>89,"100"=>77,"101"=>77); 

function getPosition($results, $StudentID) { 
    $index = 1; 
    $indexes = array(); 
    foreach ($results as $key=>$value) { 
    if ($value == $StudentID) $results[] = $index; 
    $index++; 
    } 

    return $indexes; 
} 

print_r(getPosition($results, "77")); 
+0

实际上是在搜索不是值的键。因为我返回一个特定的位置,在这个位置,数组中的一个键与函数 – 2015-03-31 12:11:51

+0

中的studentid提供的值相匹配 - 我不是100%确定我理解这个问题,但是它与之前重新排列值有关你搜索。如果你的问题是100和101交换,这可能是做什么。 – 2015-03-31 12:28:02