简体   繁体   中英

loop thru array and group values into 4 arrays based on the values

I need to group array results into 4 new arrays. Trying to group each result into the appropriate array like: top 25% mid-top 25% mid-low 25% low 25%

THIS DOES NOT WORK but that's why I'm asking how to go about it.

$top = "70000";
$mid = "40000";
$low = "25000";

$resultsarray = array(100000,75000,55000,50000,20000,5000);
echo "Top 25%:";
   foreach ($resultsarray as $value) {
   if($value >= $top){
   echo $value;
   }
}

   echo "Mid Top 25%:";
   foreach ($resultsarray as $value) {
   if($value >= $mid && $value < $top){
   echo $value;
   }
}

and so on...

array_filter will give you a smaller array based on the criteria you give.

$top = "70000";
$mid = "40000";
$low = "25000";

$resultsArray = array(100000,75000,55000,50000,20000,5000);

$top25 = array_filter($resultsArray, function ($value) use ($top) {
    return $value >= $top;
});

$midTop25 = array_filter($resultsArray, function ($value) use ($top, $mid) {
    return $value >= $mid && $value < $top;
});

$midLow25 = array_filter($resultsArray, function ($value) use ($mid, $low) {
    return $value > $low && $value < $mid;
});

$low25 = array_filter($resultsArray, function ($value) use ($low) {
    return $value <= $low;
});

function printNums(array $arr)
{
    return array_reduce($arr, function ($carry, $number) {
        return $carry .= $number .= " ";
    });
}

printf("Top 25%%: %s\n", printNums($top25));
printf("Mid-Top 25%%: %s\n", printNums($midTop25));
printf("Mid-Low 25%%: %s\n", printNums($midLow25));
printf("Low 25%%: %s\n", printNums($low25));

See it in action at https://3v4l.org/mGMOV

Replace $numbers with $resultsarray . In your previous code, the $numbers array does not exist.

Let me know if that fixed it for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM