how to get top 3 values in php array and their index - php

I want to get the highest value, the second highest value and the third highest value
For example, I have an array like:
$n = array(100,90,150,200,199,155,15,186);
I know the method to get the max value and its index:
echo max($n); //200
$maxs = array_keys($n, max($n));
echo $maxs[0]; //3
I want to get the top 3 values and their index like : value: 200, 199, 186 index:3,4,7
How can i get them?

Try this:
$n = array(100,90,150,200,199,155,15,186);
rsort($n);
$top3 = array_slice($n, 0, 3);
echo 'Values: ';
foreach ($top3 as $key => $val) {
echo "$val\n";
}
echo '<br>';
echo 'Keys: ';
foreach ($top3 as $key => $val) {
echo "$key\n";
}
Output:
Values: 200 199 186
Keys: 0 1 2

This should do the trick:
function maxNitems($array, $n = 3){
asort($array);
return array_slice(array_reverse($array, true),0,$n, true);
}
Use like:
maxNitems(array(100,90,150,200,199,155,15,186));

You can achieve it by using arsort() and array_keys() functions:
arsort() sorts an array in reverse order and maintains index association
array_keys() returns all the keys or a subset of the keys of an array
Process array:
$n = array(100,90,150,200,199,155,15,186);
arsort($n);
$keys = array_keys($n);
Get top 3 values:
echo $n[$keys[0]];
echo $n[$keys[1]];
echo $n[$keys[2]];

$n = array(100,90,150,200,199,155,15,186);
arsort($n);
$x = 0;
while (++$x <= 3)
{
$key = key($n);
$value = current($n);
next($n);
echo "Key : " . $key . " Value : " . $value . '<br>' ;
}

Easier I would think:
arsort($n);
$three = array_chunk($n, 3, true)[0];
//or
$three = array_slice($n, 0, 3, true);

try this:
public function getTopSortedThree(array $data, $asc = true)
{
if ($asc) {
uasort($data, function ($a, $b) { return $a>$b;});
} else {
uasort($data, function ($a, $b) { return $a<$b;});
}
$count = 0;
$result = [];
foreach ($data as $key => $value) {
$result[] = $data[$key];
$count++;
if ($count >= 3){
break;
}
}
return $result;
}
send false for desc order and nothing for asc order
This functionality doesn't losing keys.

Related

How to get array min value

I have multidimensional array and me need to get a minimum value.
Array may be [65,4,4,511,5,[[54,54[.[.[..].].]] and so on.
example code
<?php
$arr = [5, 1 , 2, 3, [1,5,59,47,58,[0,12,562]]];
function NumMin($arr)
{
$num = '';
foreach ($arr as $item => $i) {
if(is_array($i)){
NumMin($i);
}
else{
$num .= $i.',';
}
}
$num .= $num;
return $num;
}
$g = NumMin($arr);
var_dump($g);
I need to get 0
You can use array_walk_recursive() function to flatten a given array (makes it one-dimensional).
And use simply min() function for getting the desired output after.
array_walk_recursive($arr, function($v) use (&$res){
$res[]=$v;
});
echo min($res);
Demo
<?php
$GLOBALS["min"] = 999999; //min value int
$arr = [[[5,6],7],9,7,5, 1 , 2, 3, [1,5,59,47,58,[1,12,562]]];
array_walk_recursive($arr, 'NumMin');
function NumMin($item)
{
if(intval($item) <= intval($GLOBALS["min"]))
{
$GLOBALS["min"] = intval($item);
}
}
// The end, $GLOBALS["min"] will have the least value
echo $GLOBALS["min"];
?>

How to recursively combine array in php

I want to combine two arrays into a dictionary.
The keys will be the distinct values of the first array, the values will be all values from the second array, at matching index positions of the key.
<?php
$a=[2,3,4,5,6,7,8,9,10];
$b=[1,1,3,2,1,2,6,8,8];
?>
array_combine($b,$a);
Expected result as
<?php
/*
Value '1' occurs at index 0, 1 and 4 in $b
Those indices map to values 2, 3 and 6 in $a
*/
$result=[1=>[2,3,6],3=>4,2=>[5,7],6=>8,8=>[9,10]];
?>
There are quite a few PHP array functions. I'm not aware of one that solves your specific problem. you might be able to use some combination of built in php array functions but it might take you a while to weed through your choices and put them together in the correct way. I would just write my own function.
Something like this:
function myCustomArrayFormatter($array1, $array2) {
$result = array();
$num_occurrences = array_count_values($array1);
foreach ($array1 AS $key => $var) {
if ($num_occurrences[$var] > 1) {
$result[$var][] = $array2[$key];
} else {
$result[$var] = $array2[$key];
}
}
return $result;
}
hope that helps.
$a=[2,3,4,5,6,7,8,9,10];
$b=[1,1,3,2,1,2,6,8,8];
$results = array();
for ($x = 0; $x < count($b); $x++) {
$index = $b[$x];
if(array_key_exists ($index, $results)){
$temp = $results[$index];
}else{
$temp = array();
}
$temp[] = $a[$x];
$results[$index] = $temp;
}
print_r($results);
Here's one way to do this:
$res = [];
foreach ($b as $b_index => $b_val) {
if (!empty($res[$b_val])) {
if (is_array($res[$b_val])) {
$res[$b_val][] = $a[$b_index];
} else {
$res[$b_val] = [$res[$b_val], $a[$b_index]];
}
} else {
$res[$b_val] = $a[$b_index];
}
}
var_dump($res);
UPDATE: another way to do this:
$val_to_index = array_combine($a, $b);
$result = [];
foreach ($val_to_index as $value => $index) {
if(empty($result[$index])){
$result[$index] = $value;
} else if(is_array($result[$index])){
$result[$index][] = $value;
} else {
$result[$index] = [$result[$index], $value];
}
}
var_dump($result);

Unsort in array

Good day.
I would be like get 3 keys from $arr where value $arN[0] will be more than other...
Code:
$ar1=array(201,281);
$ar2=array(1252760,1359724);
$ar3=array(452760,34349724);
$ar4=array(1260,134344);
$ar5=array(232750,1359724);
$ar6=array(60,1439724);
$arr[]=array(6299927 => $ar1);
$arr[]=array(1252760 => $ar2);
$arr[]=array(3432444 => $ar3);
$arr[]=array(3435543 => $ar4);
$arr[]=array(7645466 => $ar5);
$arr[]=array(4574534 => $ar6);
Next function sorting array $a descending:
function cmp($a, $b)
{
if ($a == $b) {
return 0;
}
return ($a < $b) ? 1 : -1;
}
$a = array(3, 2, 5, 6, 1);
usort($, "cmp");
foreach ($a as $key => $value) {
echo "$key: $value\n";
}
outpoot: 0:6 1:5 2:4 3:2 4:1
But how change this function for my example(for my big array)?
Tell me please how make this?
How write right?
Very confusing but I think you are looking for something like this. It will give you the index of the array whose first item is greater than the first item in the next array.
foreach($arr as $key => $array) {
if($array[0] > $arr[$key+1][0]) {
echo $key;
}
}
$dates = array();
foreach ($arr as $key => $row) {
$subkeys = array_keys($row); // Elements are one-element associative arrays
$dates[$key] = $row[$subkeys[0]][0]; // Get the element, then get its [0] sub-element
}
array_multisort($dates, SORT_DESC, $arr);
print_r($arr);
$ans_array= array();
// for shuffle array without repeat
for($q=0;$q<count($arr);$q++)
{
$n = rand(0,count($arr));
if($ans_array[$n] == NULL || $ans_array[$n] == '')
{
$ans_array[$n] = $arr[$q];
}
else
{ if($q==0) $q=0;
else $q = $q-1;
}
}

php find number range of array

i have an array like this:
$d=array('good'=>10,'very good'=>20,'bad'=>1);
i want to find key from it when 13 number closest vlaue of array.
for example 16 close to 20 in $d array .
like result:
key:very good
value:20
Code
$d=array('good'=>10,'very good'=>20,'bad'=>1);
$find=13;
foreach(array_chunk($find, 5) as $val) {
echo reset($val) . "-" . end($val);
}
sorry for my english.
This is not very pretty code, but I think it does what you want it to.
$d=array('good'=>10,'very good'=>20,'bad'=>1);
$closest = array('int' => -1, 'key' => null);
$find = 16;
foreach($d as $k=>$v) {
if ($closest['int'] == -1) { $closest['int'] = abs($find-$v); $closest['key'] = $k; continue; }
if (abs($find - $v) < $closest['int']) {
$closest['int'] = abs($find-$v);
$closest['key'] = $k;
}
}
echo "key:".$closest['key']."
value:".$d[$closest['key']];
You can try
$d = array('good' => 10,'very good' => 20,'bad' => 1);
vprintf("Find:%d, Closest: %d, Grade: %s\n",findClosest($d,13));
vprintf("Find:%d, Closest: %d, Grade: %s\n",findClosest($d,16));
Output
Find:13, Closest: 10, Grade: good
Find:16, Closest: 20, Grade: very good
Function Used
function findClosest($array, $find) {
$map = array_map(function ($v) use($find) {
return abs($v - $find);
}, $array);
asort($map);
return array($find,$array[key($map)],key($map));
}
try code
$d = array('good'=>10,'very good'=>20,'bad'=>1);
$find=13;
$result = get_closest($d , $find);
echo $result;
function get_closest($array = array(), $key){
$new_arr = array();
foreach($array AS $index=>$arr){
if($key < $arr) {
$new_arr[$index] = $arr - $key;
}
else{
$new_arr[$index] = $key - $arr;
}
}
$min_val = min($new_arr);
$res = array_search( $min_val , $new_arr);
return $res;
}
thanks
you can use array_values function to get all values as $a, then you can sort $a.After sort you can find two numbers between $find, then you can compare those two numbers.

Find percentile using an array in php

I have a array like this
array(
45=>5,
42=>4.9,
48=>5,
41=>4.8,
40=>4.9,
34=>4.9,
.....
)
Here index is userid and value is his score.
Now what i want is to achieve percentile for on user for example percentile of 45,48 would be 99 and 42,40,34 would be 97 and 41 would be 94.
How i can achieve this?
Sort the array based on the "score", ascending
Percentile = (Index of an element in the sorted array ) * 100 / (total elements in the array)
Example:
<?php
$array = array(
45=>5,
42=>4.9,
48=>5,
41=>4.8,
40=>4.9,
34=>4.9,
);
print("Unsorted array:<br/>");
print_r($array);
arsort($array);
print("<br/>");
print("Sorted array:<br/>");
print_r($array);
print("<br/>");
$i=0;
$total = count($array);
$percentiles = array();
$previousValue = -1;
$previousPercentile = -1;
foreach ($array as $key => $value) {
echo "\$array[$key] => $value";
if ($previousValue == $value) {
$percentile = $previousPercentile;
} else {
$percentile = 99 - $i*100/$total;
$previousPercentile = $percentile;
}
$percentiles[$key] = $percentile;
$previousValue = $value;
$i++;
}
print("Percentiles:<br/>");
print_r($percentiles);
print("<br/>");
?>
It can be done a lot easier
function procentile($arr, $percentile=0.95){
sort($arr);
return $arr[round($percentile * count($arr) - 1.0-$percentile)];
}

Categories