我想知道如何获得数组的确定百分比。
比方说:
$array = array ("I","am","not","a","professional","coder","so","please","help","me");
它由十个值组成。
我想写一个方法来获取它的一部分。
public function get_percentage($percentage) {...;return $array_sliced;}
因此,如果我想要一个只包含"I"的数组,我会使用
$this->get_percentage(10) //10 stands for 10%
//returns $slice = array ("I");
此外,如果$num可以四舍五入到最接近的有用值,那就太好了。例如:
$this->get_percentage(8) //8 stands for 8% but the function will treat this as 10%
//returns $slice = array ("I");
我在这里没有发现任何类似的问题,希望这个问题不要太复杂。
这个方法,使用array_slice()
,应该可以帮你:
public function get_percentage($percentage)
{
$count = count($this->arr) * ($percentage / 100);
return array_slice($this->arr, 0, round($count));
}