在使用foreach循环迭代的php数组中,重复值的位置相同
下面的代码返回一个值的索引位置,该值的键与函数$haystack的参数中提供的值匹配在使用foreach循环迭代的php数组中,重复值的位置相同,php,arrays,Php,Arrays,下面的代码返回一个值的索引位置,该值的键与函数$haystack的参数中提供的值匹配 $results = array("098"=>90,"099"=>89,"100"=>77,"101"=>77); function getPosition($results,$StudentID){ arsort($results); $index = 1; $exists = ''; $keys = array_keys($results);
$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.我不知道如何让函数为两个相似的值SEG返回相同的位置。77;
编辑:函数中的StudentID参数是数组值的键。
098是数组中的一个键,它是特定StudentID的值,只需将位置作为数组返回即可
$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"));
您应该搜索值而不是键吗
$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"));
我实际上是在搜索键而不是值。因为我返回了一个特定的位置,数组中的一个键与函数OK中为studentid提供的值相匹配-我不能100%确定我是否理解这个问题,但这是否与arsort在搜索之前重新排列值有关。如果您的问题是100和101被交换,那么很可能就是这样做的。