I have a array with users sorted by score. I only want to output a specific users score (in the middle of the outputted list), and users before and after to make the list max length 10.
Like this
1. A
2. B
3. C
--------- OUTPUT START
4. D
5. E
6. F
7. G
8. H (ME)
9. I
10. J
11. K
12. L
13. M
--------- OUTPUT END
14. N
15. O
16. P
Any ideas on how to do this? Thanks in advance
Try that:
$my_rank;
foreach ($scores as $key => $value) {
if ($value == 'H') { // 'H' being your name.
$my_rank = $key;
}
}
$surroundings = array_slice($scores, max(0, $my_rank - 4), 10);
It takes the id of your name in the array and slices the array from your rank-4 with size of 10. If your rank is less than 4, it takes 0 instead (it's the max
part).
See array_slice()
$new_list = array_slice($array, 3, 10);
assuming that you've got an array of user ids like this : $arr = [0]->7364,[1]->8742,[2]->9483...
you can generate new array by:
$sibling_array = []; //new array
$myId //this user id
$myPos = array_search($myId, $arr); //position of this user
if ($myPos > 10) { // middle of list
$sibling_array = array_slice($arr, $myPos-10, $myPos+10);
} else { //close to top
$sibling_array = array_slice($arr, 0, $myPos+10);
}
$start_index =array_search("D",$your_array);
for($i=$start_index; $i<count(your_array) && $i<10; $i++)
echo($your_array[$i])