Need to get specific indices from PHP array

I created an array in PHP that contains bucnh of unix timestamps.

I am trying to create a function that will return an array containing the indices of the 3 largest numbers in this array.

For example, if the largest numbers are located at indices 3.5 and 8

And if the largest one is 5, the second largest is 8, and the smallest one is number 3, I want the order to contain the values ​​(5,8,3).

And honestly, I don't know how to do it. Does anyone know how to do this?

+1


source to share


4 answers


You can use asort to sort the array and maintain the index, then use slice along with the 4th parameter, again to maintain the index to grab the top x number of elements you are after, and finally use array_keys .



This might be a faster way, but just to show that there are many PHP array functions out there to help you achieve the effect you are looking for.

+7


source


Simon posted a simple and probably good enough way to do it.



Another option, only if you have a really large array, is to scan through the array and keep track of the indices of the three highest values ​​you see. It's O (n), but (especially because it's interpreted by PHP code and not by a compiled inline function) it's probably slower for everything but the largest array.

+1


source


In pseudocode:

function select(list[1..n], k)
     for i from 1 to k
         maxIndex = i
         maxValue = list[i]
         for j from i+1 to n
             if list[j] > maxValue
                 maxIndex = j
                 maxValue = list[j]
         swap list[i] and list[maxIndex]
     return list[k]

newarray[] = select(array, 1);
newarray[] = select(array, 2);
newarray[] = select(array, 3);

      

0


source


In PHP code:

function threeLargest($array){
 krsort($array, "SORT_NUMERIC");
 $return[0] = $array[0];
 $return[1] = $array[1];
 $return[2] = $array[2];
 return $return;
}

      

-1


source







All Articles