如何在PHP中从数组中获取前3个位置(值),包括重复

如何在PHP中从数组中获取前3个位置(值),包括重复,php,codeigniter,Php,Codeigniter,我有一个按降序排序的数组,比如值100、98、96、90…。 我正在使用foreach()循环迭代数组,并使用if条件和limit3,例如` foreach($array as $arr){ if(loop_counter<3) { echo 'something'; }} foreach($array as$arr){ 如果(循环计数器检查此问题的解决方案: $array = [100, 98, 96, 96, 95]; $count = 0; $length = count($

我有一个按降序排序的数组,比如值
100、98、96、90…
。 我正在使用
foreach()
循环迭代数组,并使用
if条件
和limit
3
,例如`

foreach($array as $arr){
if(loop_counter<3)
{ 
 echo 'something'; 
}}
foreach($array as$arr){

如果(循环计数器检查此问题的解决方案:

$array = [100, 98, 96, 96, 95];
$count = 0;
$length = count($array);
foreach($array as $key => $arr){
  if($count<3)
  { 
     echo $arr . ", ";
     if(($length != $key + 1) && $array[$key] != $array[$key + 1]) 
     {
        $count++;         
     }
  }
}
$array=[100,98,96,96,95];
$count=0;
$length=计数($array);
foreach($key=>$arr的数组){
如果($count请查看此

   $len=3;
    $selectedArray=[]
    $i = 0;

    while($i <= $len) {
 array_push($selectedArray, $array[$i]);

    if(in_array($array[$i], $array))
    {$len++;
    }

        $i++;
    }
$len=3;
$selectedArray=[]
$i=0;

虽然($i我不确定这是您想要的,但您可以使用下面的代码作为示例

$a=[10010098979796];
foreach(数组\u切片(数组\u计数\u值($a),0,3,true)为$number=>$repeat){
变量转储(数组填充(0,$repeat,$number));
}
结果

数组(2){
[0]=>
整数(100)
[1]=>
整数(100)
}
阵列(1){
[0]=>
国际(98)
}
阵列(3){
[0]=>
国际(97)
[1]=>
国际(97)
[2]=>
国际(97)
}

同样,这也会起到很好的作用

<?php

$array = array(100,98,98,98,96,96,90);
$arr_counter = 0;
$items = array();
foreach($array as $arr){


   $items[] = $arr; //capture all values in this cycle

   #get all values that are repeating then add it to a new array
   $nrr = array_unique(array_diff_assoc($items, array_unique($items)));

    #If the number is repeating again dont add to our counter $arr_counter
   if (!in_array($arr, $nrr)) {  $arr_counter = $arr_counter+1; }  

   echo $arr;  echo ' | position '; echo $arr_counter; echo '<br>';

   if  ($arr_counter == 3) { die(); }
} 


?> 

没有必要使用重复的号码consecutive@mahesh在这个问题中,您告诉我们您是按desc顺序对数组进行排序的。然后值是连续的。在循环之前,您只需要在循环语句之前按desc顺序对数组进行排序。@AnkurMishra数组是按降序在循环之前排序的。它工作正常。打开链接并单击“执行代码”进行检查k输出:
100 | position 1
98 | position 2
98 | position 2
98 | position 2
96 | position 3