I'm wondering how to get a determined percentage of an array.
Let's say:
$array = array ("I","am","not","a","professional","coder","so","please","help","me");
It's composed of ten values.
I'd like to write a method to get a slice of it.
public function get_percentage($percentage) {...;return $array_sliced;}
So if I want an array containing only "I", I'd use
$this->get_percentage(10) //10 stands for 10%
//returns $slice = array ("I");
Also, it would be great if the $num could be rounded to the nearest useful value. Eg:
$this->get_percentage(8) //8 stands for 8% but the function will treat this as 10%
//returns $slice = array ("I");
I didn't find any similar question here, hope this is not too complex.
This method, using array_slice()
, should do the trick for you:
public function get_percentage($percentage)
{
$count = count($this->arr) * ($percentage / 100);
return array_slice($this->arr, 0, round($count));
}
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.